asp.net-mvc - 在 Controller 中设置用户角色?

标签 asp.net-mvc roles

我需要能够在 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/

相关文章:

asp.net-mvc - 如何访问 _layout.cshtml 中模型的属性

javascript - MVC 5 Razor 完整 URL

asp.net-mvc - 在单声道下从 asp.net mvc 应用程序安全地运行 linux 命令行应用程序

postgresql - 更改 PostgreSQL 中组角色的默认权限

ansible - 在 Ansible 中的角色中运行具有特定标签的任务

asp.net-mvc - 将电子邮件更改保存在ASP.NET MVC的默认成员资格提供程序中

jquery - 如何在 Bootstrap 导航栏下方显示链接到的部分

c# - 声明比角色更好吗

wpf - 通过成员资格提供程序在断开连接的WPF应用程序中验证和获取Active Directory用户的角色

Symfony2 - 自定义角色