如何将角色与 user.identity.name 中的名称放在一起? FormsAuth.SetAuthCookie(strUser + "|" + strUserRole)
将用户的角色与他的名字放在一起是一个好主意吗,例如使用 setAuthCookie
,你可以:
formsAuthSrv.SetAuthCookie(strUser+strRole);
并且你可以像这样做你自己的角色提供者:
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 };
}
}
当你调用 user. Identity.name
您必须将其拆分才能仅获取用户名
有更好的选择吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议不要这么做。
IIdentity.Name
通常用于存储用户标识符,例如用户名或ID。更改其使用意味着标准代码实践(例如使用 HttpContext.User.Identity.Name)将无法按预期工作,并且在您或其他人将来维护代码时可能会造成混乱。由于
IIdentity.Name
取自 身份验证票证(默认情况下)将角色信息存储在身份验证票证的 UserData 属性中更有意义。然后,您可以在 RoleProvider 中提取此信息或为每个请求创建自定义 IPrincipal。这样
User.Identity.Name
和User.Identity.IsInRole
仍将按预期工作。此问题包含有关以下内容的更多信息使用身份验证票证的 UserData 属性来存储用户角色。
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 usingHttpContext.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
andUser.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.
这是可能的,但我认为这不是一个好主意。例如,您必须绝对确保用户名不包含 |签名,因为它会打破你们的分裂。
我建议创建一个自定义 FormsAuthenticationTicket。除了用户名之外,此票证中的值之一是 userData。您可以在此值中存储用户的角色。对于每个请求,您都可以读取此 cookie,并使用角色创建正确的身份。
请在此处查看有关此方法的更多信息: http: //msdn.microsoft.com/en-us/library/aa289844%28VS.71%29.aspx
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
您将无法使用此功能进行实时用户角色更新,他们必须注销并再次登录才能获取新角色。
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.