ASP.NET MVC 3自定义身份验证/授权

6
我已经在互联网和SO上搜索了这个主题的一些好东西,但我还有一些问题不确定:
1)我正在使用自定义身份验证提供程序的表单身份验证。所以我仍然使用Authorize属性和web.config中的部分,但基本上当FormsAuthenticationTicket不存在时,我会重定向到一个登录页面(在web.config中指定),该页面然后利用自定义身份验证提供程序对用户进行身份验证,并发放FormsAuthenticationTicket。这是正确的吗?
2)我应该使用自定义Authorize属性,还是应该在global.asax页面的Application_AuthenticateRequest事件处理程序中将GenericPrincipal注入到HttpContext中?或者我应该在控制器操作中使用User.IsInRole
我只需要基于角色的授权,而且我认为我的身份验证方案非常好。
有任何建议吗?
谢谢, 山姆
编辑
所以根据我所读的,最好的选择是创建自定义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 我有点担心在全局.asax 中使用 Application_AuthenticateRequest 和 IIS7 一起使用时会出现问题,因为每个请求都会触发该事件,包括图像、CSS、JS等。
这样是正确的吗?
1个回答

4

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")]

如果授权失败,您如何重定向到操作/视图? - Sam
1
已经想到了,只需在自定义的AuthorizeAttribute中覆盖HandleUnauthorizedRequest即可。 - Sam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接