ASP.NET MVC4 Security, Authentication, and Authorization

后端 未结 3 523
北恋
北恋 2020-12-28 10:33

I\'m working on a new asp.net mvc4 project using Visual Studio 2011 beta and am trying to get my head around the whole security thing. It\'s an internal Intranet application

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-28 10:55

    If your authentication is already being handled by Windows (I'm guessing via Active Directory), then what you're looking for is an authorization mechanism which match roles to users. One option you have is to load the user roles into the current session once successfully. Then create a custom authorize attribute that will check if the current session has the necessary roles that you're working with

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited=true, AllowMultiple=true)]
    public class CustomAuthorizationAttribute : AuthorizeAttribute
    {
       protected override bool AuthorizeCore(HttpContextBase httpContext)
       {         
          IPrincipal user = httpContext.User;
          if (!user.Identity.IsAuthenticated)
          {
              return false;
          }
    
         //check your users against a database and return true or false
          return base.AuthorizeCore(httpContext);
       }
    }
    

    Then you can use the attribute like this

    [CustomAuthorization]
    public ActionResult SomeAction()
    {
       return View();
    }
    

    UPDATE

    AuthorizeCore is the method that will be used to check whether this user should be allowed to access the respective Action Method. Within this method you can check the httpContext.User.Identity.Name property against your database or where your roles are stored. If you're using Windows Authentication via Active Directory, HttpContext.User.Identity should be an instance of WindowsIdentity

提交回复
热议问题