我需要能够在 Controller 中手动授权我的用户。
我从 AD 获取身份验证,然后在我的 Controller 中获取身份验证,
我想上 map
我从 AD 获得的用户 ID 到我的应用程序的内部用户 ID。
从UserRole表中获取userId,然后在 Controller 中设置它,但是,
不知道 Controller 中的角色如何设置?
我尝试在我的家庭 Controller 中执行此操作:
HttpContext.User = new System.Security.Principal.GenericPrincipal(User.Identity, roleName);
roleName 设置为“Admin”,但这似乎不起作用,因为它总是授权失败。
请帮忙?......
最佳答案
假设您在 Controller 方法中使用[Authorize]
,这将在操作方法之前运行,因此不会到达您必须设置角色名称的代码- 需要在调用 Controller 之前设置。
将这样的方法添加到 Global.asax 中:
protected void Application_OnPostAuthenticateRequest(Object sender, EventArgs e)
{
IPrincipal contextUser = Context.User;
if (contextUser.Identity.AuthenticationType == "Forms")
{
// determine role name
// attach to context
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(User.Identity, roleName);
Thread.CurrentPrincipal = HttpContext.Current.User;
}
}
关于asp.net-mvc - 在 Controller 中设置用户角色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3930885/