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.
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.
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.
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.