Custom Authentication and Authorization for different user types in asp.net mvc - asp.net

I’m working on a project where there are different three user types (Admin, Parent, and Teacher) that access the website. The users log in by providing their credentials and selecting their type as shown the image below
I wanted to provide a custom authentication and authorization for the users. By using the methods in this tutorial, I extended MemberShipProvider class for each user type and overrode the ValidateUser method and ended up with three classes named AdminAuthProvider, ParentAuthProvider and TeacherAuthProvider. Here is the code in the ValidateUser method in AdminAuthProvider
public override bool ValidateUser(string username, string password)
{
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
{
return false;
}
using (var db = new pscsEntities())
{
return db.Admins.Any(admin => admin.username.Equals(username) && admin.password.Equals(password));
}
}
The code for ValidateUser in the other two classes is the same.
My Questions are
- Is there a better way of doing the authentication in a single class rather than three classes which extend the same classes?
- How can I provide authorization roles in this scenario?
For the second question, the above tutorial suggests extending the RoleProvider class and overriding its methods. What I can’t seem to figure out how to override the GetRolesForUser method as it only takes a single string parameter which is the username of the currently logged in user. I’m a bit confused here.
If it helps here is the table diagrams for the three users in the database

Your solution seems to conflate two related but distinct functions: authentication and authorization.
Authentication tells you who the user is. Authorization normally occurs after authentication and tells you what the user can do, typically expressed as a list of one or more roles. Under this traditional model, you would have a single table for all three types of users and only one means of authenticating them. Once authenticated, the database will tell you what kind of roles the user has (teacher, student, or admin). Based on the roles, the web site would expose different feature sets.
Under your model, the expression of the user's roles is wound up in the authentication process. Indeed, the user himself tells you his roles as part of the authentication process. This is unusual design and is brittle for a number of reasons. For example, imagine a new type of user role (for example "teacher's assistant.") Given your current design you'd have to add a fourth DB table and domain object management functions for the new table, as well as a fourth wrapper class for the authentication code. Your design also precludes users who have more than one role (what if I'm both an admin and a teacher?)
I would suggest you revisit this design and allow the user to provide only user name and password and allow the system to determine if he is a student, teacher, or admin, or some combination of these. With this design you would need only one authentication class and GetRolesForUser would make a lot more sense.

Related

Multiple account types

I currently work on a site that must have several types of accounts
Student
Business
But companies will have different attributes, or more attributes.
How would I handle this with Identity?
If you want to use these different types as an Identity data, so you can inherit default IdentityUser class in your types. You can also use Claims or implement your own IIdentity and IPrincipal interfaces and use your magical logic to determine type of user.
One of the best (and the simplest) ways is to use roles and claims. Based on user role(s) you can determine what content is accessible to current user and what is not and also prevent access to controller methods from browser request (just typing url)

Another ASP.NET custom membership/role provider

ASP.NET 4.5 / C# / SQL 2012
I already have a well defined database with a users table and a roles/permissions column. The column contains a delimited list of roles. I was hoping to use ASP.NET's built in features on the back-end so I can be lazy and use things like the and filter by role. I'd like to read my roles from the database and tell ASP these are the roles my user is in. Custom...but hopefully simple. Here is what I have so far:
//create an identity
GenericIdentity objIdentity = new GenericIdentity("Matt"); //this would actually be the username/email of the newly authenticated user
//get roles for user
string[] strRoles = { "ADW", "USR" }; //this will get read from the database on authentication
//add identity and roles to a principal
GenericPrincipal objPrincipal = new GenericPrincipal(objIdentity, strRoles);
//add to current user
HttpContext.Current.User = objPrincipal;
//add the principal to the current context of the current thread
Thread.CurrentPrincipal = objPrincipal; //not sure what this does, doesn't affect my results/tests
If I execute the code above and then run the following:
Response.Write(User.IsInRole("ADW"));
Response.Write(User.IsInRole("xxx"));
I get a True/False as expected. However, this doesn't persist to the next page. I did a fair amount of reading on custom membership/role providers, but I can't find this specific use case. Most talk about setting up a DB specifically for this task. I also saw mention of the newer Simple Membership, but couldn't get any love from that end either. I'm hoping there is a solution that involves what I'm already doing. I'd love to execute this code when the user authenticates, but be able to reference this user in other pages. I could always call to the database for every page. I'm assuming that would suck, and that's not what the built in provider does.
Thanks all.
You are approaching it from the wrong side. You don't have to create identity and principal manually, assuming you are not creating a custom authentication module.
In any other case, you only choose the persistence mechanism and the corresponding authentication module sets the identity/principal according to the persistence.
A commonly used persistence mechanism is Forms Authentication, where you issue forms cookies. The forms authentication module makes sure the identity/principal is set early in the pipeline and takes the cookie as the source of information.
If you want to replace the cookie by your custom cookie (in other words - replace forms authentication with your own) - you have to think of a way to persist the security info, to the cookie for example.
Note, however, that this is probably not necessary. The very same forms authentication can be used with any custom membership and role providers. This is because these two have different responsibilities - membersip provider is for actual authentication whereas forms authentication module is for persisting the information for consecutive requests.
Edit: to add a role for a user so that it is persisted in the user database:
Roles.AddUsersToRoles( ... );
But first, you'd have to create users in the user database:
Membership.CreateUser( ... );
Note that Roles and Membership are facades for actual role and membership providers. While default providers use the membership database, you can easily create custom providers that persist the information anywhere at the server side.

How can I check for authorization when using forms authentication?

I am developing an ASP.NET website. I am planning to use Forms authentication in order to guarantee authentication/authorization, but I am facing two problems regarding the authorization:
I know how to set in the web config that the authenticated users are allowed to visit a webpage (say myPage.aspx). But I do not know how to define that UserA is able to access myPage to retrieve his information, not UserB's information.
I was thinking about generating a token when the user authenticates, so I am able to check to whom this token belongs to and verify if this information is available to him.
What do you think about this approach? Does the Form Authentication generates a token like that? (I couldn't find any mention about it in my research). If not, could I adapt the Form authentication mechanisms in order to generate or would I need to write everything on my own?
I would like to access webservices, and these should only return information if the user is logged. For this reason, I would like to use the same token explained above. What do you think about it? Is it a good approach?
I am asking this because I have no experience on designing authentication/authorization mechanisms, any help/hint would be appreciated.
Regarding question one, after forms authentication occurs in an ASP.Net web forms app, the user's identity is exposed as a FormsIdentity object in the Page.User.Identity property. This object has a Name property which contains the username that a user use to log into your site. You can use this value to restrict what a user can access. For example, let's say you have a table in your database with user information containing the following fields:
userId int
userName varchar(25)
...more fields containing user information...
You can restrict a user to only access information from the row in this table in which the userName equals the Page.User.Identity.Name property, either directly if you are using direct ADO.Net or via your query to your ORM-mapped (i.e. nHibernate or EF) domain object.
Regarding question two, the FormsIdentity object exposed by Page.User.Identity has a boolean "IsAuthenticated" property. You can use this to restrict access to your web service as follows:
if(Page.User.Identity.IsAuthenticated)
{
//Call your web service in a secure manner
}

How do integrate "Users" in my DDD model with authenticating users?

I'm creating my first ASP.NET MVC site and have been trying to follow domain driven development. My site is a project collaboration site where users can be assigned to one or more projects on the site. Tasks are then added to projects, and users with in a project can be assigned to tasks. So a "User" is a fundamental concept of my domain model.
My plan is to have a "User" model object which contains all the information about a user and can be accessed through an IUserRepository. Each user can be identified by a UserId. Although I'm not sure at this point if I want the UserId to be a string or integer.
How should my domain objects User and IUserRepository relate to the more administrative functions of my site like authorizing users and allowing them to login? How would I integrate my domain model with other aspects of ASP.NET such as HttpContext.User, HttpContext.Profile, a custom MemberShipProvider, a custom ProfileProvider, or custom AuthorizeAttribute?
Should I create a custom MembershipProvider and or ProfileProvider which wraps my IUserRepository? Although, I can also foresee why I may want to separate the User information in my domain model from the authorization of a user on my site. For example in the future I may want to switch to windows authentication from forms authentication.
Would it be better to not try and reinvent the wheel and stick with the standard SqlMembershipProvider built into ASP.NET? Each user's profile information would be stored in the domain model (User/IUserRepository), but this would not include their password. I would then use the standard ASP.NET membership stuff to handle creating and authorizing users? So there would need to be some code somewhere that would know to create a profile for a new users in the IUserRepository when their account is created or the first time they login.
Yes - very good question. Like #Andrew Cooper, our team also went through all this.
We went with the following approaches (right or wrong):
Custom Membership Provider
Neither I or the other developer are fans of the built in ASP.NET Membership provider. It's way too bloated for what our site is about (simple, UGC-driven social website). We created a very simple one that does what our application needs, and nothing more. Whereas the built-in membership provider does everything you might need, but most likely won't.
Custom Forms Authentication Ticket/Authentication
Everything in our application uses interface-driven dependency injection (StructureMap). This includes Forms Authentication. We created a very thin interface:
public interface IAuthenticationService
{
void SignIn(User user, HttpResponseBase httpResponseBase);
void SignOut();
}
This simple interface allows easy mocking/testing. With the implementation, we create a custom forms authentication ticket containing: things like the UserId and the Roles, which are required on every HTTP request, do not frequently change and therefore should not be fetched on every request.
We then use an action filter to decrypt the forms authentication ticket (including the roles) and stick it in the HttpContext.Current.User.Identity (for which our Principal object is also interface-based).
Use of [Authorize] and [AdminOnly]
We can still make use of the authorization attributes in MVC. And we also created one for each role. [AdminOnly] simply checks the role for the current user, and throws a 401 (forbidden).
Simple, single table for User, simple POCO
All user information is stored in a single table (with the exception of "optional" user info, such as profile interests). This is mapped to a simple POCO (Entity Framework), which also has domain-logic built into the object.
User Repository/Service
Simple User Repository that is domain-specific. Things like changing password, updating profile, retrieving users, etc. The repository calls into domain logic on the User object i mentioned above. The service is a thin wrapper on top of the repository, which seperates single repository methods (e.g Find) into more specialized ones (FindById, FindByNickname).
Domain seperated from security
Our "domain" the User and his/her's association information. This includes name, profile, facebook/social integration, etc.
Things like "Login", "Logout" are dealing with authentication and things like "User.IsInRole" deals with authorization and therefore do not belong in the domain.
So our controllers work with both the IAuthenticationService and the IUserService.
Creating a profile is a perfect example of domain logic, that is mixed with authentication logic also.
Here's what our's looks like:
[HttpPost]
[ActionName("Signup")]
public ActionResult Signup(SignupViewModel model)
{
if (ModelState.IsValid)
{
try
{
// Map to Domain Model.
var user = Mapper.Map<SignupViewModel, Core.Entities.Users.User>(model);
// Create salt and hash password.
user.Password = _authenticationService.SaltAndHashPassword();
// Signup User.
_userService.Save(user);
// Save Changes.
_unitOfWork.Commit();
// Forms Authenticate this user.
_authenticationService.SignIn(user, Response);
// Redirect to homepage.
return RedirectToAction("Index", "Home", new { area = "" });
}
catch (Exception exception)
{
ModelState.AddModelError("SignupError", "Sorry, an error occured during Signup. Please try again later.");
_loggingService.Error(exception);
}
}
return View(model);
}
Summary
The above has worked well for us. I love having a simple User table, and not that bloated madness that is the ASP.NET Membership provider. It's simple and represents our domain, not ASP.NET's representation of it.
That being said, as i said we have a simple website. If you're working on a banking website then i would be careful about re-inventing the wheel.
My advice to use is create your domain/model first, before you even think about authentication. (of course, this is what DDD is all about).
Then work out your security requirements and choose an authentication provider (off the shelf, or custom) appropriately.
Do not let ASP.NET dictate how your domain should be designed. This is the trap most people fall into (including me, on a previous project).
Good luck!
Let me break down your collection of questions a bit:
Although I'm not sure at this point if I want the UserId to be a string or integer.
It doesn't have to be an integer per say, but definitely use some kind of bit based value here (e.g. int, long or guid). An index operating over a fixed size value is much faster than an index over a string, and in your life time, you will never run out of identifiers for your users.
How should my domain objects User and IUserRepository relate to the more administrative functions of my site like authorizing users and allowing them to login?
Decide if you want to use the built in asp.net membership or not. I recommend not for the reason that it's mostly just bloat and you have to implement most of the features of it yourself anyway, like email verification, which you'd think from looking at the tables generated it would be built in... The template project for ASP.NET MVC 1 and 2 both include a simple membership repository, just rewrite the functions that actually validate the user and you'll be well on your way.
How would I integrate my domain model with other aspects of ASP.NET such as HttpContext.User, HttpContext.Profile, a custom MemberShipProvider, a custom ProfileProvider, or custom AuthorizeAttribute?
Each one of these is worthy of it's own SO question, and each has been asked here before. That being said, HttpContext.User is only useful if you are using the built in FormsAuthentication functionality and I recommend using it in the beginning until you encounter a situation where it is does not do what you want. I like storing the user key in the name when signing in with FormsAuthentication and loading a request bound current user object at the beginning of every request if HttpContext.User.IsAuthenticated is true.
As for the profile, I avoid stateful requests with a passion, and have never used it before, so someone else will have to help you with that one.
All you need to use the built in [Authorize] attribute is to tell FormsAuthentication the user is valdiated. If you want to use the roles feature of the authorize attribute, write your own RoleProvider and it will work like magic. You can find plenty of examples for that on Stack Overflow. HACK: You only have to implement RoleProvider.GetAllRoles(), RoleProvider.GetRolesForUser(string username), and RoleProvider.IsUserInRole(string username, string roleName) in order to have it work. You do not have to implement the entire interface unless you wish to use all of the functionality of the asp.net membership system.
Would it be better to not try and reinvent the wheel and stick with the standard SqlMembershipProvider built into ASP.NET?
The pragmatic answer for every derivation of this question is to not reinvent the wheel until the wheel doesn't do what you need it to do, how you need it to do it.
if (built in stuff works fine) {
use the built in stuff;
} else {
write your own;
}
if (easier to write your own then figure out how to use another tool) {
write your own;
} else {
use another tool;
}
if (need feature not in the system) {
if (time to extend existing api < time to do it yourself) {
extend api;
} else {
do it yourself;
}
}
I know my answer comes a little bit late, but for future references to other colleagues having the same question.
Here is an example of Custom Authentication and Authorization using Roles as well.
http://www.codeproject.com/Articles/408306/Understanding-and-Implementing-ASP-NET-Custom-Form. It's a very good article, very fresh and recent.
In my opinion, you should have this implementation as part of the infrastructure (Just create a new project Security or whatever you want to call it) and implement this example above there. Then call this mechanism from your Application Layer. Remember that the Application layer controls and orchestrate the whole operation in your application. Domain layer should be concern exclusively about business operations, not about access or data persistence, etc.. It's ignorant on how you authenticate people in your system.
Think of a brick and mortar company. The fingerprint access system implemented has nothing to do with this company's operations, but still, it's part of the infrastructure (building). As a matter of fact, it controls who have access to the company, so they can do their respective duties. You don't have two employees, one to scan his fingerprint so the other can walk in and do its job. You have only an Employee with an index finger. For "access" all you need is his finger... So, your repository, if you are going to use the same UserRepository for authentication, should contain a method for authentication. If you decided to use an AccessService instead (this is an application service, not a domain one), you need to include UserRepository so you access that user data, get his finger information (username and password) and compares it with whatever is coming from the form (finger scan). Did I explain myself right?
Most of DDD's situations apply to real life's situations... when it comes to architecture of the software.

Roles for white-label service access

Okay,
I know I'm doing something wrong - but can't figure out a better way.
I am developing a website which is going to allow users to setup their own mini-websites.
Something like Ning.
Also, I have only 1 basic login and access to each mini website is provided (right now) via roles.
So the way I am doing this right now is:
Everytime a new mini website is created - say blah, I create 2 roles in my application.
blah_users and blah_admin
The user creating the mini website is given the role - blah_admin and every other user wanting to join this mini website (or network) is given the role - blah_user.
Anyone can view data from any website. However to add data, one must be a member of that mini site (must have the blah_user role assigned)
The problem that I am facing is that by doing a role based system, I'm having to do loads of stuff manually. Asp.Net 2 controls which work on the User.IsAunthenticated property are basically useless to me now because along with the IsAuthenticated property, I must also check if the user has the proper role.
I'm guessing there is a better way to architect the system but I am not sure how.
Any ideas?
This website is being developed in ASP.Net 2 on IIS 6.
Thanks a tonne!
I afraid standard roles-related stuff of ASP.NET is not what you need. You can try to change authentication module so it will:
Log you in with cookie.
Determine what roles does your visitor have. Perhaps you will use some special table that corresponds user and site.
Make custom principal with user roles enumerated and assign Identity and Principal to the current request.
I also don't think that making special roles for each site is good idea. When you would have hundred sites, you would also have two hundred roles. Pretty unmanageable, I afraid.
When we were solving similar task, we were just not using standard controls. We had single set of roles used on all sites. Membership of concrete user is determined according to current site and his relations to this site.
Addition: Another possibility to investigate is Application that exists in ASP.NET authentication system. Maybe it's possible to isolate each subsite into separate application?
Update: Method that works for our application.
Do not make a lot of cloned roles. Use only two: users and admin. If your sites are public then "users" role could be just global - user on one site doesn't differ from user on another site. If "users" and "everyone" are different roles, then of course "users" should also be bound to a site.
Use standard ASP.NET Membership users, but do not use standard role mechanism.
Make a mechanism for storing relation between site and user. It could be simple table that holds site id, user is and role.
What you have to override is IsInRole method. (Methods to be exact, i'll cover it later). This method is in IPrinciple interface, so you have to make your own principal object. It's quite simple.
Method IsInRole of this type should look take current site (from HttpRequest) look into the site-user table and get roles
Then you have to associate your principal with a request. Do it in PostAuthenticateRequest event.
There is also RoleProvider. Honestly I'm not sure when is it used, but it also have IsInRole method. We can override it in the same way. But other methods of this provider are harder. For example AddUsersToRoles. It accepts array of user names and roles, but to what context (site) should it be added? To current? Not sure, because I don't know when this method is called. So it requires some experiments. I see (Reflector helps) that RopePrincipal by itself uses RoleProvider to fetch list of roles, so maybe it's implement only RoleProvider, using standard principal. For our application this is not a case, so I can't say what problems could be hidden here.

Resources