Saturday, August 20, 2016

Role Based access to Method with Spring Security @PreAuthorize


In this blog i am going to show how to implement role based method permission with Spring Security. Here i am showing "@PreAuthorize"  and its integration,

 To start with let me show you the dependencies which needs to be there in your project to start. I am using spring Spring 4.x. Apart from basic spring jars you need to have following jar which is specific to spring security in your project.
  1. spring-security-config jar
  2. spring-security-core jar
  3. spring-security-web jar


Once these jar files are added to the project, following changes needs to be done in step wise manner to better understand their purpose and understanding.

Step1:
  Add following code to applicationContext.xml or configuration file which you are using.

Add namespace details in xml file.

xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-4.0.xsd"
Add following bean tags to enable security feature
<security:global-method-security pre-post-annotations="enabled">
  <security:expression-handler ref="expressionHandler"/>
</security:global-method-security> 
<bean id="expressionHandler" class="org.springframework.
security.access .expression.method.DefaultMethodSecurityExpressionHandler">
     <property name="permissionEvaluator" ref="permissionEvaluator"/>
</bean>  
<bean id="permissionEvaluator" class="com.sample.security.SampleMethodPermissionEvaluator"/>

security:global-method-security:  This tag will enable method level security using spring configuration.
expressionHandler :This parameter will be mapped to class "DefaultMethodSecurityExpressionHandler" out of the box provided by spring.
This bean will take property named permission evaluator this property will take reference for custom Method evaluator which will have method to validate the access role.

Step2: Create Method evaluator class which will have method to validate the role permission.
package com.sample.security;

import java.io.Serializable;

import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

public class SampleMethodPermissionEvaluator implements PermissionEvaluator {

 public SampleMethodPermissionEvaluator() {
  super();
 }

 @Override
 public boolean hasPermission(Authentication authentication, Object targetDomainObject, 
Object exeMethodRole) {
  boolean hasPermission = false;
  if (authentication != null && exeMethodRole != null && exeMethodRole instanceof String) {
   for (GrantedAuthority auth : authentication.getAuthorities()) {
    if (exeMethodRole.equals(auth.getAuthority())){
     hasPermission = true;
     break;
    }else {
     hasPermission = false;
    }
   }
  }
  return hasPermission;
 }
 @Override
 public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType,
   Object exeMethodRole) {
  throw new Exception("Not supported by this application");
 }
}  

hasPermission method in the above class will have permission check, you need to ensure that Authentication object is available in context. So that it is available to the method.

Step3: Add the following line to any of the interface methods.
@PreAuthorize("hasPermission(#user,'admin')")
Here is sample code.
@PreAuthorize("hasPermission(#user,'admin')")
 boolean createUser(String userDetails);

#user will be populated with the Authentication object by spring framework. Second parameter is the role which is allowed for the method.

You are good to go, start your application and test the method access. If logged in user does not have permission then it will throw "AccessDeniedException", this you need to handle and show proper message to the user.





No comments:

Post a Comment

Components of Big Data - Hadoop System

In this blog i will explain important components which are part of Hadoop System. I will give very brief overview of these components. Be...