SimpleMembership - anyone made it n-tier friendly? - simplemembership

"SimpleMembership", we're told, is the future of asp.net membership / role management.
The MVC4 "Internet Application" template implements Account management using SimpleMembership. However, the way it is implemented merges all the application tiers into 1.
It kind of shocked me that after all the work they've put into layering apps properly with MVC, we get this shoddy implementation of "the way forward" for Membership with no DI, use of WebMatrix DLLs and complete lack of SoC. Particularly the ActionFilterAttribute for SimpleMembershipInitialization - it inherits from an MVC attribute and makes calls to the EF DBContext directly.
I realise I'm being lazy, but has anyone done a "proper" template using SimpleMembership that means I can have proper separated tiers in my app, and not have EF DBContext references in my MVC app?

One of powerful concepts of SimpleMembership is that you can customize the user profile to fit your application needs, as discussed in this article. For example, you may want to add email confirmation to your registration process which will require storing the user's email address in the user profile. In the previous membership/role management for ASP.NET this was very ugly to implement and added properties were stored in a blob. Yuck!
So what does this have to do with your question on making SimpleMembership n-tier friendly? While I agree that what the template generates is not n-tier friendly I would also state that most real MVC applications of any complexity will require customizing SimpleMembership, and therefore will require making a tier or layer that is specific to the application requirements anyway. Stated another way, creating a reusable tier for SimpleMembership would only be useful in the most basic MVC apps.
Personally I have come to the conclusion that what is generated by the Internet template in regards to SimpleMembership will almost always be modified. As the first article I referenced points out the first part of customization is getting rid of the SimplemembershipInitialization attribute, which is just a lazy way of initializing SimpleMembership in the event the developer is not using forms authentication. And often you will want to move the DBContext used by SimpleMembership into the DBContext for the rest of your application. User profiles are often tightly integrated with the rest of the application domain.
And since we are on the subject of SoC and ASP.NET security, I would argue that ASP.NET was never very good at this. For forms authentication you use an Authorize attribute on your controllers and/or actions which takes a role as a parameter. This forces the application developer to think about security design while designing the application domain. You have to determine what roles the application will have up front, and heaven forbid they change later because now you have to go through all of those attributes and update them accordingly. I have started to use a custom authorize attribute that takes as parameters a resource name and an operation type (ex: read, write, execute...). Then I can map roles to resource/operations in a database so that it can change easily, or even allow an administrator to make changes to how roles are implemented in the application. Microsoft is taking the same approach with ClaimsPrincipalPermissionAttribute now that they have incorporated WIF into .NET 4.5.
Updated 3/8/2013
I have created an open source project on CodePlex called SimpleSecurity that decouples SimpleMembership from the MVC application. You can read about it here. I still think developers will most likely want to modify SimpleSecurity but since this is open source they can. We will see if this is something we can evolve to be a reusable and better SimpleMembership.

Accepted answer is not correct, that is not N-Tier. The membership data access and business logic are occurring in the same layer. Just because code is in a different assembly doesn't mean it isn't in the same layer.
Without some kind of transport mechanism to the data access layer, this is not N-Tier.
The solution is to inherit and override the WebMatrix SimpleMembershipProvider class such that its data access calls can be performed on a separate host.
I recommend using dotPeek to look at SimpleMembershipProvider so you know what to do in your overrides.

I think your question relates more to SoC than n-tier architecture (which is more about physical separation between layers as pointed out by #klatzib).
I would argue that the logic within the membership providers should not be classed as business logic as they do not contain application or client specific code. In fact the idea of the provider model is that it fulfils a generic contract irrespective of the context in which it's used. A common mistake developers make is extending MembershipProvider and bolting in application specific business logic that should exist in a higher layer. If that's what you want to achieve with a alternative design, then that's the wrong approach. Providers are plugins for the .NET framework, and should be entirely abstracted from code. They certainly shouldn't contain your application domain, and you should very rarely need to extend them.
Addressing your question another way, does the SimpleMembershipProvider prohibit SoC in application design or even n-tier architecture? No it doesn't. The MVC4 template is built for simplicity, but the ActionFilter used to initialize the provider is not part of the membership implementation, and you are free to initialize the the provider in any way you see fit (I prefer making this call from a DI container factory method). In fact SimpleMembershipProvider as no direct dependency on EF at all, so yes it is possible to remove references to EF DbContext in your web app.

Exactly what I was looking for (almost). Just wish it wasn't tied into entity frameworks as I was hoping to get Kevin's n-tier solution working with Dapper ORM :(

Related

What is a good architecture to add an API to an existing ASP.Net Core 2.2 MVC solution

When I started development of my current project I had no knowledge or prior experience of web development, ASP.Net (Core), C#, JS and so on.
With a lot of reading, excercising and testing I now have an ASP.Net Core 2.2 web application with multi-tenancy based on the database-per-tenant strategy hosted on Azure with Azure SQL as backend.
I have a solution with 2 projects:
the MVC web application that also has the .Net Core Identity from which I use the individual user accounts stored in ASPNet... tables (I did implement my custom UI, mainly so I could use the Localization middleware already used throughout the application)
a data layer that contains the db context's, the data models and the repository
Now I need at add an API.
The sole purpose of the API is cleary defined: give customers(tenants) the possibility to import and export data, most likely connected to other customer's application(s). This API will not be used by the UI. The API will not be hit with thousands of queries per second. It will be part of a business solution with 50 to 200 customers who will perform occassional import/export actions.
I have already implemented Identity and the authentication for the API should be done against the users setup in Identity but with a different authentication mechanism.
I have done a fair bit of searching and reading and found many tutorials/blogs on how to create a WebAPI with .Net Core but they all start from a new project and never go much more into depth. The once that really go in-depth are too complex for me ...
I have 3 questions unanswered at the moment although I know that there's probably more than 1 good answer to each of the questions but I think these are the likes of questions that many in my position, beyond the newbie/beginner but not yet a seasoned veteran, have and are searching for so I hope this post helps not just me but many others as well.
Question 1 - Architecture, where to create the API (project)?
There are 3 possibilities:
1 Add APIControllers to the MVC application (organize API-related classes in separate folders)
Benefits
quick and easy, everything else is already in place
deploys with the solution
Concerns
as it is part of the solution it becomes very monolithic, less flexible
Questions
can I implement a second authentication/authorization mechanism next to the implemented individual user accounts? (more detailed in the second question which is all about security)
2 Add a WebAPI project to the solution
Benefits
better separation but can still use/reference the resources of the other projects
probably gives benefits for scaling and tuning?
Questions
can I implement a second authentication/authorization mechanism next to the implemented individual user accounts leveraging the Identity of the MVC project? (more detailed in the second question which is all about security)
is this project separately published to Azure (or any cloud provider for that matter) using the www.example.com/api path (virtual directory) or is the solution published a whole?
3 Create a separate solution with the WebAPI project and include the data layer project
Benefits
full separation although sharing the use of the data layer project
completely independent with regards to deployment, scalability etc.
Concerns
maybe adds a layer of unnecessary complexity (the API will not handle thousands of requests per second)
Everything that is already configured/setup in the MVC project and that is required will need to be redone
Questions
can I include the data layer project in the solution (it is then part of 2 solutions) or should I reference it as a dll?
Question 2 - how to implement Authentication/Authorization that resides side-by-side with the Identity individual user account?
This is related only to the first 2 options of the architecture as in the third option the project would be on it's own.
The basic question is how to setup more than one authentication mechanism, one for UI users and another for API access.
First there is the choice of Authentication, most of tutorials blogs talk about JWT and Auth (OAuth?). I am not asking what the "best" solution is but which solution would be "preferred" by B2B customers who are the only ones that will use the API.
I am not sure how to redirect to the right authentication: when a request is sent to an API controller method with the Authorize attribute and the user hasn't been authenticated yet it needs to reply with an error.
Currently if a method with the Authorize attribute is executed by an unauthenticated user the user is redirected to the login page as configured in startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
services.PostConfigure<CookieAuthenticationOptions>(IdentityConstants.ApplicationScheme,
opt => {
opt.LoginPath = "/User/Login";
...
Do I need to configure this with something like the example I found below:
app.UseWhen(x => (x.Request.Path.StartsWithSegment("/api", StringComparison.OrdinalIgnoreCase)),
builder =>
{
builder.UseMiddleware<AuthenticationMiddleware>();
});
or is this configured in a different way?
In the case of creating the API as a separate project should I use the "Multiple startup projects" option? I guess this means that I need to create the whole startup.cs again?
Question 3 - if I want to offer my customers a REST API and an OData API, can I handle this through a single API or do I need to develop a second to support OData?
I know it is lengthy but I'm sure that others are looking for similar information and I'd appreciate any input.
Thanks

ASP.Net core Identity - Overkill for basic login system?

I need to create a very basic log in system to allow access to an admin portal.
I'll need to hold email, password and a field to identify access level (admin, read-only or edit).
Users will be created by an admin, where they will get sent an email with a generated password. There will be no user registration page.
Asp.net core Identity would handle all this...but my question is it overkill for a small application?
That is really a matter of opinion. I don't mind overkilling small tasks, as I learn a lot in the process. If it's a system between a small group, you could just implement a reset-button for you, that resets whoever you want, and generates a new random password. I have done that in the past.
Also .Net Core Identity handles a lot of the boilerplate code, so it's not that difficult to implement. There are a lot of great guides out there.
...but my question is it overkill for a small application?
Depends on your definition of an overkill.
It will allow you to setup working identity system in a few clicks, so from that point of view, having to code all that stuff from scratch would be an overkill.
On the other hand, the generated tables have a few excess (for your use case) columns that might seem like an overkill. There is also support for functionality like 2FA, which you may not need.
Bottom line: by choosing to use the identity system, you save time and gain some extraneous functionality.
I have been using .net for a very long time, and for a long time implemented custom user management (overriding built in providers, and customising to my own database structures etc) This is required if implementing over legacy system but for new development and security, it worth using off-the-shelf authorization/authentication systems whether it's built in or supported by .Net or using 3rd party services.

Is there any built-in manager for handling CRUD operations of tables from ConfigurationDbContext(Clients, Resources...)?

I'm very new with those things, so I have some problems with understanding and figuring out which approach to use.
Currently, I am using .NET Core 3.1 and IdentityServer4 in my project. I am configuring my authorization server and there I have some controllers for creating users, clients etc.
In the controller for users handling I am using UserManager for all of the CRUD operations. Is that better approach than using dbContext?
I have created controller for handling clients as well. For this purpose, I am using ConfigurationDbContext, since I have not found some kind of a built-in manager for handling this.
Do you have some better solution? I am thinking of creating managers for this. Is there some example of that?
I want to create controllers which would function in the similar way, to have similar behavior, response results, validations etc.
Thank you for your help.
As far I as know UserManager comes with ASP.Net core Identity which is the way Microsoft gives built-in functionality to manage Manages users, passwords, profile data, roles, and others.
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-3.1&tabs=visual-studio
You can find Stores under IdentityServer4 namespaces like IClientStore and IResourceStore and more, so those interfaces have a similar Idea of userManager for users in Identity.
This is the source code https://github.com/IdentityServer/IdentityServer4/tree/master/src/Storage/src/Stores
Anyway there is an AdminUi that you can take a look to see if you find something helpful https://www.identityserver.com/documentation

ASP.NET MVC 5 simple login

I need simple log in functionality in my project (logged in users can access and modify their profile). I've read a book "PRO ASP.NET MVC 5" by Adam Freeman where he quickly written a simple, short and elegant login mechanism just by using authorization and authentication filters and extending from some built-in classes. However, I just checked the internet and found many completely opposite approaches using classes such as Identity and Claim and achieved by writing LOTS of code, i.e. this or this.
Is it really necessary to implement a huge framework and write many lines of code just for a simple log in approach with some security? Is it really that bad to rely on authentication and authorization filters?
Yes, I am planning on publishing my project, but it's really very small.
What would be the best and the most beneficial practice for creating a basic log in functionality?
when you create asp.net mvc 5 webapp you will find asp.net-identity already exist you just have to make simple changes in the user to link it to your other entites

How to combine Web Api and MVC best in a single web app

I am about to create a simple web app and I am wondering if I should use ASP.NET MVC 4 new feature Web API.
What's the best way to do this ?
I've done some researches and I found out there are two option :
Option 1
Make the Web Api my service layer and call it from the controller to read/write data, and render the view using view models and razor.
Option 2
Make the Web Api my service layer and call it directly from the view using Javascript.
I am not a big fan of Option 2 since I feel like I am neglecting the controller which will be used only for redirection between pages. Besides I prefer using razor rather than Javascript.
And If I choose Option 1 will I have to make an instance of one Web API in the controller? because this feels like I am doing something wrong.
What's the best option ? Is there any other options I haven't considered ?
And if you can give some references or books which can help me, I would appreciate it.
Thanks.
I usually have another layer (which can be a different project/assembly depending on the size and complexity of your application) for my business rules. You can call this business services, or whatever works on your case.
So both MVC controllers and API controllers use this layer; which keeps the application dry.
I personally prefer to only keep complex operations in my business layers, which means if I need to read something from my persistence layer to display in my views, I do it directly on the MVC controller. This is a matter of personal preference but I prefer to go the CQRS way.
So you MVC controllers are going to instantiate these business services (or they will be injected into your controllers if you are using IoC). For read operations you can choose to go straight to your persistance layer or use another read strategy.
The same will happen to your API controllers, they will use this "common" layer of services.
You don't need to instantiate your API Controllers on your MVC Controllers.
Consuming your Web Api controllers via AJAX is ok if you are developing a SPA or similar.
There is no a single way to structure your application, there are just different ways and every one has more or less pain attached.
If you are considering introducing tests in your applications (and you should :)); then you should structure it in a way it is easy to test each part of it.
Just my 2 cents.
The whole point of Web API is to be a stateless RESTful service. There would never be an instance of it if you're doing it right. I realize this question is old and you may personally have learned this, but the answer isn't as much for you as it is an answer to a frequently-asked question.
Note that when speaking of Web API, more often than not, people are talking about ApiControllers and not basic MVC "Controllers" that take routes and turn them into Views.
So in your project, you may have some "Controllers" which do some basic view logic, but no business logic. Don't confuse that with your Service Layer which is a wrapper for your Business Logic and Persistence access.
I, and many, am of the opinion that ApiControllers shouldn't be mixed with your MVC application. Keep in mind that MVC does not mix well with Web API. As Filip W says:
Many of the concepts used by Web API and MVC, even though similar at
first glance, are actually not compatible. For example, Web API
attributes are System.Web.Http.Filters.Filter and MVC attributes are
System.Web.Mvc.Filter - and they are not interchangeable.
Most flexible answer
So what you do is create a subdomain named api.YourWebsite.com, and build a new Web API ApiController project there. That Web API Project should do NOTHING more than instantiate and expose Business Logic via ApiControllers and Dependency Injection.
Alternative 1
Service-Oriented Architecture is all about reusability. If you want to keep your applications DRY, you should definitely fall into SOA. Though, every situation is different. If you will never ever use the same business logic in this website in any other application (desktop, android, tablet, ewPhones, etc), then you have an alternative method.
Create your Busines Logic Layer as a different Project, and access it directly from your web app. When your Javascript (Angular/Razor?) Controllers make a call, they can call into your ViewModels and/or Codebehind or something similar, which can instantiate Business Logic and directly access it. No need for services if everything is right there and won't be reused.
Alternative 2
Go ahead and put your Web API ApiControllers in the same project. But, be sure you separate them into different folders from your MVC "Controllers." Still, when your Javascript Controllers make a call, they will be making Routing calls to your website for stateless returns. Do not mix the stateless ApiControllers with your ViewModels and other MVC code.
The downside to this is a lack of SOC. Now you have Service-Layer and UI-Layer mixed, and your UI-Layer is forced to access your Business Logic Layer (DLL). What's wrong with that if Alternative 1 did it?
Well, what's wrong is that Alternative 1 was a small application with no room for growth. Anything else (The original plan, or Alternative 2 here) should have UI's that have no clue whatsoever that Business Logic (or Persistence) even exist. They should go about their doodies unawares of the backend world.