views:

48

answers:

3

is it a good idea to keep the user's role together with his name, like when you do setAuthCookie you do:

formsAuthSrv.SetAuthCookie(strUser+strRole);

and you can do your own roles provider like this:

public class MyRoleProvider : RoleProvider
    {
        public override string[] GetRolesForUser(string username)
        {
             // get the roles from username and return it as an string[]      
..     
                return new string[] { role };
        }
    }

and when you do user.identity.name you have to split it to get just the username

So, what do you think, is it ok ?

+1  A: 

You wouldn't be able to do live user role updates with this, they would have to log out and in again to pick up new roles.

ck
I don't need live user role updates
Omu
+2  A: 

This would be possible, but I don't think this is a good idea. For example, you would have to make absolutely sure the Username does not contain a | sign, for it will break your split.

I suggest creating a custom FormsAuthenticationTicket. One of the values in this ticket, besides the username, is userData. In this value you can store the roles of the user. With every request, you can read this cookie, and create a correct Identity with the roles.

Check here for some more info about this method: http://msdn.microsoft.com/en-us/library/aa289844%28VS.71%29.aspx

Pbirkoff
good link, but, is it going to work with cookie-less users ?
Omu
+2  A: 

I would advise against it. IIdentity.Name is usually used to store a user identifier such as a user name or ID. Changing its use will mean standard code practices such as using HttpContext.User.Identity.Name will not work as expected and could be confusing when you or others are maintaining your code in the future.

As the IIdentity.Name is taken from the authentication ticket (by default) it would make more sense to store the role information in the UserData property of the authentication ticket.

You could then extract this information in your RoleProvider or create a custom IPrincipal for every request. That way User.Identity.Name and User.Identity.IsInRole will still work as expected.

This question contains more information about using the UserData property of the authentication ticket to store user roles.

David G