How do I manually set a user's role in ASP.NET MVC?
Asked Answered
H

4

18

This project I'm working on requires me to keep a local db of admin users and use an external db for regular users. Anyone who passes authentication in the admin db should be assigned the 'admin' role, and anyone authenticated through the other db will always be assigned a 'user' role.

Can I manually assign these roles? I don't need the complexity of a Role Provider or anything, since I'm only using these two roles which will ALWAYS be based on which db they authenticate with.

It would be a HUGE help if you could provide sample code or a link to some documentation. Thanks!

EDIT:

Currently I am not using the role provider and creating one seems like a hassle. I know its not 'best-practice', but I only need to assign 1 of 2 roles during login (this will never change). It also doesn't make sense to store role information in the database, since users are already separated into 2 dbs by their role.

Here's some pseudo-code:

if (AdminDB.ValidateUser(username,password)==true) {
     SetAuthCookie(username);
     AssociateUserWithRole(username, 'admin');
} elseif (UserDB.ValidateUser(username,password)==true) {
     SetAuthCookie(username);
     AssociateUserWithRole(username, 'user');
} else {
     // Login failed.
}

Its the 'ThisSession.AssociateUserWithRole' part I don't know. Basically, one the user is authenticated, I need to tell .NET which role the user belongs to.

Harewood answered 19/8, 2009 at 2:25 Comment(0)
M
16

Implementing a role provider is not particularly hard -- especially if you are only implementing the role checking, not the role management. Just implement those portions that you need and have the rest throw NotImplementedExceptions. If you only have one application you need not be too concerned about that portion either. Note that the portions that you need will be dictated by how the framework uses it, not how you would use it. I think for example you will need to implement the bit that returns all the user's roles even if you only want to check if they are in a specific role.

That said, you could omit the whole RoleProvider and do the whole thing in the Session. In this case you'd implement your own AuthorizeAttribute and replace it's authentication and role-checking bits with your own. Store the user's role in the session once authenticated and check it there using your attribute and the parameters supplied to the attribute for the method/class you've decorated it with.

Myriagram answered 19/8, 2009 at 2:52 Comment(7)
The custom AuthorizeAttribute makes the most sense to me (a .NET MVC noob from PHP-land). Thanks for the help!!Unmeant
Is your mean using Session as this?: in login-> Session.Add("LoggedInRole", "admin"); and when I need current user's type,read it from Session. Is Session secure enough to save user type(role) in it?Aliquant
@MajidR Session is typically all server-side so it's no less secure than the role provider, from an intrusion perspective. You'd obviously have to code all the logic yourself so, from a robustness perspective, it would depend. I'd probably go the RoleProvider route.Myriagram
Indeed,I now developed my web application using Session for current user role(type);can you clearly say to me that is needed to edit all my project and use ASP.NET built in Roles?Aliquant
@MajidR I'm not sure what you're asking. To use the built-in role handling, you can use an existing role provider implementation (ASP has Active Directory and SQL providers out of the box) or create your own, then use it in conjunction with the AuthorizeAttributeMyriagram
excuse me for headache;I'm asking that "Should I worry about application security ,that I am using Session for storing current user's type?".Aliquant
@MajidR again, I'm not sure what you're asking. Using Session won't absolve you from worrying about security, including having appropriate permissions for accessing restricted actions. On the other hand, access to the Session is restricted (the code can't access another user's Session from yours) so it seems like a safe albeit more generic, less robust way to do it if used naively. Unless you're really sure what you're doing you may want to use one of the existing providers. Configuration of an existing provider is less challenging than constructing your own.Myriagram
I
6

If you are using the membership & roles built into asp.net then look at the AddUserToRole and RemoveUserFromRole:

http://msdn.microsoft.com/en-us/library/system.web.security.roles.addusertorole.aspx

Based on how they login you can add and remove them as needed.

I couldn't tell from your post if you aren't using the role provider or if you were saying you didn't want to create your own role provider. If you aren't using the built in role provider then you will have to use whatever coding mechanism you have in place to switch the user at login based on how / where they login from.

EDIT: Now that you have shown your code and have stated you are not using the asp.net roles engine.

You are using the forms auth cookie it appears so override the authenticateRequest of the global.asax file and set the roles up as needed and create your ticket.

Here's a sample in: http://csharpdotnetfreak.blogspot.com/2009/02/formsauthentication-ticket-roles-aspnet.html

The sample only "gets" the roles but you can add/change the roles here.

Illtempered answered 19/8, 2009 at 2:33 Comment(1)
I think @tvanfosson's solution would work best for what I need. Thanks for the help though! I appreciate it.Unmeant
I
2

I believe this article (although from 2003) clearly describes the process of assigning roles to a user, and replacing the principal on every request (similar to what NerdDinner does):

Authorizing Users with Role-Based Security: http://msdn.microsoft.com/en-us/library/aa289844%28v=vs.71%29.aspx

Incumber answered 21/9, 2011 at 19:35 Comment(0)
D
2

If someone encounters the same problem with OWIN, I guess this may help:

var identityResult = await manager.CreateIdentityAsync(login, "MyAppCookie");

if (<user is admin>)
    identityResult.AddClaim(new System.Security.Claims.Claim(identityResult.RoleClaimType, "Admin"));
else
    identityResult.AddClaim(new System.Security.Claims.Claim(identityResult.RoleClaimType, "User"));

HttpContext.Current.GetOwinContext().Authentication.SignIn(identityResult);
Deplume answered 2/6, 2016 at 10:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.