User Authorization in Spring MVC

We have an application in which users can be created by the administrator and assigned roles for a specific type of entity.

For example, if the object is called Student , application users have different privilege levels, for example:

  • BROWSE - View Student Information
  • EDITOR - Editing student information
  • EXPORTER - Export Student Data

The URIs for performing the above actions are as follows:

  • GET - /content/{classId}/{studentId}/view
  • PUT - /content/{classId}/{studentId}
  • GET - /content/{classId}/{studentId}/export
  • POST - /content/{classId}/{studentId}/export

Note that URIs are dynamic. In addition, the user EXPORTER can be assigned the role of VIEWER for Class 1 and EXPORTER for Class 2 .

In my spring-security configuration, I defined only two rules - ADMINISTRATOR and USER .

  • ADMINISTRATOR - access to all
  • USER - access to everything except the URI /admin/* .

VIEWER , EDITOR , EXPORTER roles are not spring roles. Now I am faced with a problem, restricting user access to resources on which they do not have rights.

In addition, if the user does not have EXPORTER , he should not even see the "Export" button (placed somewhere in the application). Perhaps I can do this with the spring security tag. But this is another problem.

I can make them spring-security aware, but the question is where can I put my reading logic {studentId} ( @PathVariable ) and match it with the current logged-in user to see if he has access to him.

I even thought about creating a filter / HandlerInterceptor that listens for /content/* . But I will have to do ugly things, for example, parse the URI, extract the second path parameter myself and then check the database.

Is there a more elegant way for spring-security to do this?

Any thoughts are welcome.

+4
source share
1 answer

you can provide spring security with your own SecurityExpressionHandler implementation. Just DefaultWebSecurityExpressionHandler and override createSecurityExpressionRoot . By default, this method returns an instance of WebSecurityExpressionRoot . Your implementation can simply extend this class and add additional methods that you would use in your spring security configuration.

this is how you provide your own implementation of SecurityExpressionHandler. The code comes from spring security documentation :

 <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="myPermissionEvaluator"/> </bean> 

Does the answer provide sufficient information or do you need more help?

+3
source

All Articles