加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 如何在MVC3上使用authorize属性

发布时间:2020-12-16 00:05:56 所属栏目:asp.Net 来源:网络整理
导读:我已经读过要在MVC上使用属性[Authorize],你只需将它放在一个动作或你要保护的控制器类上. 我的问题是:Authorize属性如何知道用户是否已登录?我是否必须提供任何Session对象才能让Authorize知道用户是否获得授权? 解决方法 此属性通过查看HttpContext.Use
我已经读过要在MVC上使用属性[Authorize],你只需将它放在一个动作或你要保护的控制器类上.

我的问题是:Authorize属性如何知道用户是否已登录?我是否必须提供任何Session对象才能让Authorize知道用户是否获得授权?

解决方法

此属性通过查看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;
    }

这是some more info on FormsAuthentication.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读