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.