【问题标题】:ASP.NET MVC 3 Custom Authentication/AuthorizationASP.NET MVC 3 自定义身份验证/授权
【发布时间】:2011-10-10 19:57:41
【问题描述】:

我在整个互联网上进行了搜索,我发现了一些关于这个主题的好东西,但是我有几个问题我仍然不确定:

1) 我将表单身份验证与自定义身份验证提供程序一起使用。所以我仍然使用Authorize 属性和web.config 中的部分,但基本上当FormsAuthenticationTicket 不存在时,我重定向到登录页面(在web.config 中指定),然后使用自定义身份验证提供程序针对数据库对用户进行身份验证,然后发出FormsAuthenticationTicket。这是正确的吗?

2) 我应该使用自定义Authorize 属性还是应该将GenericPrincipal 从global.asax 页面中的Application_AuthenticateRequest 事件处理程序注入HttpContext?或者我应该在控制器操作中使用User.IsInRole insode?​​p>

我只需要基于角色的授权,我认为我的身份验证方案非常好。

任何指针/建议?

谢谢, 山姆

编辑

所以根据我的阅读,最好的选择是创建一个自定义 AuthorizeAttribute 并覆盖 AuthorizeCore

所以我所做的是这样的:

public class CustomAuthorize : System.Web.Mvc.AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext.User.Identity.IsAuthenticated)
            {
                var model = AdminUserViewModel.FromJsonString(((FormsIdentity)httpContext.User.Identity).Ticket.UserData);
                httpContext.User = new GenericPrincipal(HttpContext.Current.User.Identity, model.SecurityGroups.Select(x => x.Name).ToArray());
            }
            return base.AuthorizeCore(httpContext);
        }

        protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
        {
            //base.HandleUnauthorizedRequest(filterContext);
            filterContext.Result = new System.Web.Mvc.RedirectResult("/Authentication/NotAuthorized", false);
        }
    }

只需使用存储在FormsAuthenticationTicketUserData 属性中的角色注入一个新的主体/身份。然后让基地完成剩下的工作。

这看起来可以吗?

编辑#2

我有点厌倦在 IIS7 中使用 global.asax 中的 Application_AuthenticateRequest,因为集成管道,每个请求都会触发该事件、图像、css、js...

这对吗?

【问题讨论】:

    标签: asp.net asp.net-mvc-3 authorization


    【解决方案1】:

    1) 我做同样的事情。

    2) 我使用 Authorize 属性和 Application_AuthenticateRequest 事件处理程序。

    在 Application_AuthenticateRequest 事件处理程序中,我执行以下操作:

        string[] roles = authenticationTicket.UserData.Split(',');
    
        if (Context.User != null)
            Context.User = new GenericPrincipal(Context.User.Identity, roles);
    

    在控制器或操作级别,我会执行以下操作:

        [Authorize(Roles = "Admin, SuperAdmin")]
    

    【讨论】:

    • 如果授权失败,您如何重定向到操作/视图?
    • 想通了,只需覆盖自定义AuthorizeAttribute 中的HandleUnauthorizedRequest
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多