如何在MVC3上使用授权属性

9
我读到过,在MVC中使用属性[Authorize],你只需要将其放置在你想要保护的操作或控制器类上即可。
我的问题是:如何让Authorize属性知道用户是否已登录?我是否需要提供任何Session对象以让Authorize知道用户是否被授权?
2个回答

15

这个属性通过检查HttpContext.User.Identity.IsAuthenticated来工作。

如果你正在使用类似FormsAuthentication的东西,如果用户在他们的计算机上有一个有效的FormsAuthentication cookie(可以通过使用FormsAuthentication.SetAuthCookie添加),那么这将被设置为true。

如果你对Authorize的内部工作感兴趣,这是来自发布的Microsoft源代码:

protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
        if (httpContext == null) {
            throw new ArgumentNullException("httpContext");
        } 

        IPrincipal user = httpContext.User; 
        if (!user.Identity.IsAuthenticated) { 
            return false;
        } 

        if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {
            return false;
        } 

        if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) { 
            return false; 
        }

        return true;
    }

这里有有关FormsAuthentication的更多信息


4

默认情况下,授权属性类需要将HttpContext作为参数进行调用。然后它会检查HttpContext.User.Identity.IsAuthenticated布尔值并根据其行事。这仅适用于使用Forms身份验证的情况。如果您正在使用自己的登录逻辑(例如在会话对象中),则可以从Authorize属性派生一个类并对其进行调用。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true,     AllowMultiple = true)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        clsSession sess = httpContext.Session["Current"] as clsSession;
        if (sess.IsLogin) return true;
        return false;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new ViewResult { ViewName = "Unauthorized" };
    }
}

然后您可以像这样使用这个类:
[MyAuthorize]
public ActionResult Index()
{
    return View();
}

这个会起作用。在所有控制器操作中,您可以使用[MyAuthorize]代替[Authorize]。如果它返回false,它将返回一个视图(在这种情况下为“未经授权”)。视图名称可以是任何内容,并且可以位于views / shared文件夹中。


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