ASP. net mvc provides AuthorizeAttribute to control the security of Controller actions. However, the role or user specified by this attribute is written in the code rather than in the configuration file, which is not flexible enough.
In order to be able to control permissions more flexibly and fine-grained, some method is required to control permissions in the configuration file (such as web. config) to modify the application authorization by modifying the configuration file without re-compiling the code. In a simple scenario, [CustomAuthorize (Roles = "Manager")] differs from the built-in [Authorize (Roles = "Manager: the subsequent permission control is completed through Membership Provider, that is, whether the current user has the permission to use Context. user. isInRole ("Managers"). The first one is that the custom ActionFilter completes permission control by reading configuration items.
Don't talk nonsense, go to the Code:
1. inherit from the system's built-in AuthorizeAttribute (Note: AuthorizeAttribute itself inherits from FilterAttribute and implements the IAuthorizationFilter Interface ):
Public class CustomAuthorizeAttribute: AuthorizeAttribute {
......
}
2. override one of the key methods: AuthorizeCore
1 protected override bool AuthorizeCore (HttpContextBase httpContext ){
2...
3}
4
5 private static bool UserInRole (string role ){
6 if (user. IsInRole (role ))
7 return true;
8 return false;
9}
3. Implement custom authorization:
Protected override bool AuthorizeCore (HttpContextBase httpContext ){
If (httpContext = null ){
Throw new ArgumentNullException ("httpContext ");
}
IPrincipal user = httpContext. User;
If (! User. Identity. IsAuthenticated ){
Return false;
}
Var rolesInSetting = ConfigurationManager. AppSettings ["RolesFor:" + Roles];
Var usersInSetting = ConfigurationManager. receivettings ["UsersFor:" + Users];
If (! String. IsNullOrEmpty (usersInSetting )){
Var users = usersInSetting. Split (newchar [] {','}, StringSplitOptions. RemoveEmptyEntries );
If (users! = Null | users. Length> 0 & users. Contains (User. Identity. Name, StringComparer. OrdinalIgnoreCase ))
Return true;
}
If (String. IsNullOrEmpty (rolesInSetting ))
Returnfalsevar roles = rolesInSetting. Split (newchar [] {','}, StringSplitOptions. RemoveEmptyEntries );
If (roles = null | roles. Length <= 0)
Returnfalse;
If (roles. Any (t => UserInRole (t ))
Returntrue;
Returnfalse}
4. The configuration file web. config
<Add key = "RolesFor: Manager" value = "admins, managers"/>
<Add key = "UsersFor: Manager" value = "hackee, bill"/>
5. Configure the Action method:
[CustomAuthorize (Manager)]
Public ActionResult GetSecureData (){...}