我已经读过要在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; }
原文地址:https://www.jb51.cc/aspnet/251434.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。