在Asp.Net MVC 3中,AuthorizeAttribute的认证用户是什么?

Ing*_*als 1 c# forms-authentication authorize-attribute asp.net-mvc-3

我发现Asp.Net中的很多东西都是基于假定的知识.例如,我对互联网认证不太了解,并且很难在初学者层面上找到任何关于它的信息.

令我困惑的一件事是AuthorizeAttribute.我理解如何使用它以及它应该做什么,但我想知道它是否适用于你有自定义登录系统的情况.

在AuthorizeAttribute页面的描述中,它简单地说 When you mark an action method with AuthorizeAttribute, access to that action method is restricted to users who are both authenticated and authorized.

那么什么是经过身份验证的用户,如何设置一个用户进行身份验证.如果我创建自己的登录系统,我该如何设置是为了使登录用户的身份验证足以让AuthorizeAttribute允许他进入?

TWi*_*ars 5

它检查的IsAuthorized 的IIdentityIPrincipal的.

在Global.asax中添加一个处理"AuthorizeRequest"的方法.然后在那个方法做你需要检查用户是否被授权(检查会话,cookie,数据库等)

然后将HttpContext.Current.User设置为GenericPrincipal,该GenericPrincipal具有实现IIdentity并将其IsAuthorized设置为true的用户.

像这样的东西:

  public class MvcApplication : HttpApplication
  {
    public MvcApplication()
    {
      this.AuthorizeRequest += this.AuthorizedRequestEvent;
    }

    private void AuthorizedRequestEvent(object sender, System.EventArgs e)
    {
      // do checking here with what ever you want
      bool isAuthenicated = false;

      // change this what what ever implements IIdentity
      var user = new User(); 
      user.IsAuthenticated = isAuthenicated ;
      GenericPrincipal principal;
      principal = new GenericPrincipal(user, new string[] { });
      HttpContext.Current.User = principal;
    }
   }
Run Code Online (Sandbox Code Playgroud)

  • +1 - 很好的答案,而不告诉OP"去买书或你缺乏基本知识" (2认同)