如何使用上MVC3授权属性 [英] How to use authorize attribute on MVC3

查看:140
本文介绍了如何使用上MVC3授权属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过,使用 [授权] MVC的属性,你就必须把它放在一个动作或过要保护控制器类。

I've read that to use the attribute [Authorize] on MVC, you just have to place it over an action or over the controller class you want to secure.

我的问题是:如何在授权属性知道,如果用户登录或不?我是否有提供任何Session对象为了让授权知道,如果一个用户被授权?

My question is: How does the Authorize attribute know if a user is logged or not? Do i have to provide any Session object in order to let Authorize know if a user is authorized?

推荐答案

这属性的工作原理是在看 HttpContext.User.Identity.IsAuthenticated

This attribute works by looking at HttpContext.User.Identity.IsAuthenticated.

如果你使用像FormsAuthentication,这将是如果用户在其计算机上的有效FormsAuthentication饼干(您可以通过添加<一个设置为true href=\"http://msdn.microsoft.com/en-us/library/twk5762b.aspx\"><$c$c>FormsAuthentication.SetAuthCookie).

If you're using something like FormsAuthentication, this will be set to true if the user has a valid FormsAuthentication cookie on their machine (which you can add by using FormsAuthentication.SetAuthCookie).

如果您有兴趣授权的内部工作,这是从微软公布的源$ C ​​$ C:

If you're interested in the inner-workings of Authorize, this is from the published Microsoft source code:

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 一些更多的信息。

Here is some more info on FormsAuthentication.

这篇关于如何使用上MVC3授权属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆