Question

User's authority is frequently changed in my web service.
In this case, how do I check user's authority effectively?

I wrote code that check user's authority in every controller temporarily. But I think this way would not good for maintenance.

How do I check user's authority without writing checking method in every controller?

Was it helpful?

Solution

Not sure what you are doing - Spring Security automatically keeps track of authorities in the User's security context. If you need to programmatically check for some other reason, then implement the HandlerInterceptor interface, and in the preHandle method, call SecurityContextHolder.getContext().getAuthentication() to get the current user. You can then check the User's authorities.

The interceptor would be configured as follows:

<mvc:interceptors>
    <bean class="com.my.package.MyInterceptor" />
</mvc:interceptors>

OTHER TIPS

Add an intercept-url element to your config with the role that is required, eg.

<http auto-config='true'>
  <intercept-url pattern="/**" access="ROLE_FOO" />
</http>

Use HandlerMethodArgumentResolver to let Spring inject GrantedAuthority in the controller method. If a user can have more than one authority then you will need to create a class to hold user's authorities (can be named as GrantedAuthorities). After you are done, your controller method will look something like this:

@RequestMapping({"/xyz"})
public String handleXYZRequest(GrantedAuthorities authorities) {
    /* use authorities if not null */
    ...
}

In resolver, you will use the same code that your are currently using to get authorities and it will return either null or GrantedAuthorities object. If you are using older version of Spring then use WebArgumentResolver and register it with AnnotationMethodHandlerAdapter.

Above approach avoids duplication of code and it can be used to inject anything you need from SecurityContextHolder in controller methods.

Edit

This is similar to the approach used by greenhouse. Please see WebConfig, where principal (which is Account object) is injected in controller through argument resolver.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top