How to Perform Activity Based Authorization Using Spring Security

Posted By : Vishal Kumar | 03-Sep-2017

Spring framework provides us two annotation for securing our rest apis @Secured and @PreAuthorized but these both annotations are compatible with role based authorization. If we want to perform activity based authorization then we can not use @Secured annotation. For performing activity based authorization we have to write some extra code. So i am going to tell you how to perform activity based authorization with Spring Security and how to make secure our rest apis for perticular activity.

 

Step 1: First of all we have to create a PermissionAssigner class for assigning permissions for the roles. I this class i am using a map to put diffrent-diffrent permission for the prticular role.

public class PermissionAssigner {
        private static Logger LOGGER = LoggerFactory.getLogger(PermissionAssigner.class);
        private static final Map<Role, Map<String, String>> PERMISSION;

        static {
            LOGGER.info("Permission assigner is executed");
            Map<Role, Map<String, String>> mainPermissionMap = new HashMap<Role, Map<String, String>>();
            /*************** User permission *********************/

            Map<String, String> userPermissionMap = new HashMap<String, String>();
            userPermissionMap.put("PERM_GET_LOGGEDIN_USER_DETAIL", "Getting his own detail");
            mainPermissionMap.put(Role.ROLE_USER, userPermissionMap);

            /*************** Delegate Admin permission *********************/

            Map<String, String> delegateAdminPermissionMap = new HashMap<String, String>();
          delegateAdminPermissionMap.putAll(supportUserPermissionMap);
          delegateAdminPermissionMap.put("PERM_DISABLE_USER", "Disable the user");
            mainPermissionMap.put(Role.ROLE_DELEGATE_ADMIN, delegateAdminPermissionMap);

            /*************** Super Admin permission *********************/

            Map<String, String> superAdminPermissionMap = new HashMap<String, String>();
           superAdminPermissionMap.putAll(delegateAdminPermissionMap);
           superAdminPermissionMap.put("PERM_CREATE_DELEGATE_ADMIN", "Creating a new delegate admin");
            mainPermissionMap.put(Role.ROLE_SUPER_ADMIN, superAdminPermissionMap);

        PERMISSION = Collections.unmodifiableMap(mainPermissionMap);
    }

    public static Map<Role, Map<String, String>> getPermissions() {
        return PERMISSION;
    }
    public static Map<String, String> getPermissionsByRole(Role role) {
        return PERMISSION.get(role);
    }
}

Step 2: Now we have setted the permissions for the roles then we have to pass these permissions in the authorities. Because we have already implemented spring security in my previous blog http://www.oodlestechnologies.com/blogs/Spring%20Security%20with%20Token%20Based%20Authentication so i am not telling here how to implement spring security. But whent we implement spring security we have to override getAuthorities method of Authentication class so now we are going to use this method.

@Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Role role = user.getRole();

        List<GrantedAuthority> authList=new ArrayList<GrantedAuthority>();
        Map<String,String> permissions = new HashMap<String,String>(PermissionAssigner.getPermissionsByRole(role));

        for(Map.Entry<String,String> m:permissions.entrySet()){
            authList.add(new SimpleGrantedAuthority(m.getKey().toString()));
        }
        return authList;
    }

Here we are getting the roles of user in our first line inside the method. These roles are stored in database when we created any user now we are just getting the role of that user and then getting the permission for this perticular role.

 

Step 3: This is the last step and it is very simple now we have to just use @PreAuthorize annotation with our rest api like below example.

@PreAuthorize("hasAuthority('PERM_GET_LOGGEDIN_USER_DETAIL')")
    @RequestMapping(value=UrlMapping.GET_LOGGER_IN_USER,method=RequestMethod.GET)
    ResponseEntity<Object> getLoggedInUser(){

        User loggedInuser = GenericUtils.getLoggedInUser();
        Map<String,Object> map= userService.getUserById(loggedInuser.getId());
        return ResponseHandler.generateResponse(HttpStatus.OK, false,messageService.getMessage(Message.USER_INFO_LOGGEDIN), map);
    }

Now this api is secured with the prmission and only that role can access this api who has the permission of GET_LOGGEDIN_USER_DETAIL.

 

Conclusion : So making the activity based authorization is not very much difficult. We can also improve the functionality of this activity based authorization for making a blocked map and remove that permissions from the permission map who are blocked.

 

About Author

Author Image
Vishal Kumar

Vishal Kumar is Master in Computers Application. He has good technical skills in Java and always motivated to learn new things.

Request for Proposal

Name is required

Comment is required

Sending message..