authentication - ASP.NET MVC4 覆盖 OnAuthorization 以允许角色白名单

标签 authentication asp.net-mvc-4 authorization

我有一个具有两种类型角色的 ASP.NET MVC4 站点:管理员和合作伙伴。

基本上,对站点的所有访问都需要用户进行身份验证并具有管理员角色。 因此我在 FilterConfig.cs(从 Global.asax 调用)中这样做:

public class FilterConfig {
    public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new AuthorizeAttribute { Roles = "Administrator" }); // default deny
    }
}

然而,对于一个 Controller ,我想向具有合作伙伴角色但没有管理员角色的用户授予访问权限。我知道我可以通过不使用全局过滤器而是在每个 Controller 或操作上设置授权属性来做到这一点,但我想要一种白名单方法,而不是默认情况下所有访问都需要“管理员”角色,然后使用某种形式的白名单.

我试过使用一个 Controller ,我像这样覆盖 OnAuthorization:

public class MyController : Controller {
    protected override void OnAuthorization(AuthorizationContext filterContext) {
        if (User.Identity.IsAuthenticated) {
            var attributes = new List<AllowRolesAttribute>();
            attributes.AddRange(filterContext.ActionDescriptor.GetCustomAttributes(true).OfType<AllowRolesAttribute>());
            attributes.AddRange(filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(true).OfType<AllowRolesAttribute>());
            foreach (var authorizationAttribute in attributes) {
                foreach (var role in authorizationAttribute.Roles.Split(',')) {
                    if (User.IsInRole(role))
                        return; // Skip authorization because user has one of the allowed roles.
                }
            }
        }
        base.OnAuthorization(filterContext);
    }
}

然后我这样定义 Controller :

[AllowRoles(Roles = "Partner")]
public class HomeController : MyController
{
    ...

但这行不通。当我使用角色为“合作伙伴”的用户访问此 Controller 时,我可以按照代码进入内部返回语句,但用户仍被重定向到登录页面而不是被授权。我在这里缺少什么?

最佳答案

不确定您是否使用表单例份验证。可能需要这样的东西?

[AllowRoles(Roles = "Partner")]
public class HomeController : MyController
{     
    FormsAuthentication.RedirectFromLoginPage( "User", false );
    .
    .
    .
}

关于authentication - ASP.NET MVC4 覆盖 OnAuthorization 以允许角色白名单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12803139/

相关文章:

.net-4.0 - 为什么在新的 MVC4 项目中会出现编译错误?

ruby-on-rails - Ruby on Rails 单点登录与多个企业环境

python - Django 1.2 : login issue (GET parameter: next)

c# - Razor MVC 获取 SQL 语句的选择选项 ID

rest - 在 ZF2 中授权不成功时如何跳过 Controller 操作

reactjs - react SPA中的魔术链接身份验证

android - 与在Android上提供API的Node.js服务器建立安全连接

authentication - iframe 和 api 的 OAuth 2 身份验证

javascript - 从 node.js 移植 MD5 去

azure - Windows Azure、MVC 4.0应用程序如何维护状态?这是使用 TempData 的最佳实践吗?