ASP.NET MVC 5 simple login - authentication

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

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

What pitfalls or consequences could there be when structuring a solution in 3 projects (.net core, vue.js and webapi)?

I want to make a quick, safe and nice application.
For many years I have been programming in PHP and regular ASP. But wanted to go on with .NET and vue.js.
So I have an idea, I wanted to create and plan to do it like this:
I was thinking of using hosting from an external service.
Then I would have three projects:
domain.com/index - Vue.js which will be a SPA, where the user can filter through a catalog, press like and send few api requests (mainly get-requests).
secure.domain.com - Here I will have a .net mvc project where I can use identity. This will make it simple to handle/register users. I will also give the correct session here for authenticated users. And it will affect domain.com/index, where they only are allowed to do some of the things if they are logged in
api.domain.com - This will be the webapi api. Only authenticated users will be allowed to send some of the requests.
I have used several weeks at looking into how to structure this.
But as I do not have much experience with this.
What pitfalls and bad consequences do you see in structuring it like this?
Are there any heads up you want to give me? Or any other recommendations?
I have been trying to melt all of this together in one project, but that has been difficult, because they operate in different ways. So now I have ended up with this, and look forward to
Size of project
It will be a relative small project.
People should be able to register/authenticate themselves (through facebook/google/server login).
Authenticated People should be able to add records(links) to a database. When adding this to the database they may also want to upload files, and choose some additional information.
All people should be able to filter through the catalog of records (5000+) ( Here I am using vue.js/vuex/axios). Here they should be able to comment too on links too.
Webapi will have 8 entities/tables and one view which will GET all the information. 3 tables should be able to have POST.
So it is more or less a catalog, where people should be able to add records and find new ones.
I was planning to use the identity from asp.net core 3.1. It is a "template" where I can easily add 3rd party logins. (https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-3.1&tabs=visual-studio)
Additional questions:
Can you tell me how request from SPA will be authenticated in your API? (Jwt or cookie)? Why would you like to have a separate identity service, also Why you would like to use asp.net identity (is it because of ease of setup)?
I have not been thinking about authenticating API requests. Was thinking to only have authenticated users who can send POST-requests. And the rest will be get requests. Limited only from the server. Should I have some additional authentication? Does JWT make web APIs safe enough for my use?
Was thinking of using .net identity because it is simple. And I don't want to use time on setting it up.
Since this is your first project of this type, I would recommend to keep it simple.
Just create one web site. Otherwise you might get issues with the cookies not working for subdomains and you will also get issues with CORS. That is, you will get all problems at the same to time (configuration issues, infrastructure issues and the pain from writing the application itself).
You can still have a clean separation by using sub folders (or Areas in MVC) and by using class libraries for the backend (API) business logic.
Once you have mastered the basics (i.e. writing the actual application) you can start looking at other means of separation etc.

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

MVC4 and Simplemembership

I am somewhat of a novice application developer, certainly very new to MVC4 and have been through a number of handy tutorials to learn the core principles of MVC. I do get lost with terminology as someone who is entirley self taught.
I am trying to replace an application I wrote previously that uses ASP.net membership which I was able to create myself. This application is an issue logging and reporting system that does a lot with an SQL database.
I have no concern dropping all the users and rebuilding the user database in the new simplemembership provider. Although, I am not sure where to start.
I feel as though using the ready made "internet application" template means I end up with loads of files / folders I do not need (or understand), so my question is, how to I start with MVC4 and simplemembership, ideally without using the "internet application" template.
Thank you.
The Internet template does not add that many unnecessary files. It will add controllers, views, and models you will need for handling user log-on and registration. If you start from an Empty MVC project you will have to create these items from scratch. If you want to start from scratch I would take a look at the open source project SimpleSecurity that decouples SimpleMembership from your MVC application. There is an article here that describes this approach which will make it easier to incorporate SimpleMembership into an Empty MVC project. You can look at the example in the SimpleSecurity project so you can copy the controllers, views and models you will need. The example adds email confirmation and other features that are not available in the Internet template.
There are some unnecessary files, but it depends on how you define "unnecessary".
If you don't care about signing in with a facebook or google account, and you don't care about WebApi, and you don't care about knockout.js and other stuff, you're free to delete it. You can use Nuget to uninstall the Webapi stuff. And you can also remove the OpenId stuff, but you will have to modify your AccountController to remove the code that makes use of it.
It would help if you could ask specific questions.. vague questions like this are hard to answer because we don't know what's unnecessary for you.
Thanks for your help, I know my question was vague, but I was only able to build my new site from an empty template by following this guide.
I have changed a few things (i.e. an instance of SQL rather than local DB) and it all worked.
How to add ASP.NET Membership Provider in a Empty MVC 4 Project Template?

SimpleMembership - anyone made it n-tier friendly?

"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 :(