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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 如何在MVC3上使用authorize属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经读过要在MVC上使用属性[Authorize],你只需将它放在一个动作或你要保护的控制器类上.

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

解决方法

属性通过查看HttpContext.User.Identity.IsAuthenticated来工作.

如果您使用的是FormsAuthentication,如果用户的计算机上有一个有效的FormsAuthentication cookie(您可以使用FormsAuthentication.SetAuthCookie添加),则会将其设置为true.

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

  1. protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
  2. if (httpContext == null) {
  3. throw new ArgumentNullException("httpContext");
  4. }
  5.  
  6. IPrincipal user = httpContext.User;
  7. if (!user.Identity.IsAuthenticated) {
  8. return false;
  9. }
  10.  
  11. if (_useRSSplit.Length > 0 && !_useRSSplit.Contains(user.Identity.Name,StringComparer.OrdinalIgnoreCase)) {
  12. return false;
  13. }
  14.  
  15. if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) {
  16. return false;
  17. }
  18.  
  19. return true;
  20. }

这是some more info on FormsAuthentication.

猜你在找的asp.Net相关文章