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?
I would advise against it.
IIdentity.Nameis usually used to store a user identifier such as a user name or ID. Changing its use will mean standard code practices such as usingHttpContext.User.Identity.Namewill not work as expected and could be confusing when you or others are maintaining your code in the future.As the
IIdentity.Nameis 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.NameandUser.Identity.IsInRolewill still work as expected.This question contains more information about using the UserData property of the authentication ticket to store user roles.