我已经读过要在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;
- }