spring-securityauthority

what's the best way to check user's current authority in spring3 controller methods?


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?


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>