0

Is it a good idea to keep the user's role together with his name, for example with setAuthCookie, do you:

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 call user.identity.name you have to split it to get just the username

Is there a better alternative?

lhan
  • 4,585
  • 11
  • 60
  • 105
Omu
  • 69,856
  • 92
  • 277
  • 407
  • yeah, what they said. membership and roles are related but very seperate facets of the asp.net provider stack. the first thing that came to my mind when I read this is 'step away from the keyboard, omu. you are about to enter a world of pain.' trust me. lol. Maybe take some time an consider what each provider is actually doing for you and the way may become more evident. good luck. – Sky Sanders Feb 22 '10 at 23:05

3 Answers3

2

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
  • 4,642
  • 2
  • 20
  • 18
2

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.

Community
  • 1
  • 1
David Glenn
  • 24,412
  • 19
  • 74
  • 94
1

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.

cjk
  • 45,739
  • 9
  • 81
  • 112