Chinmay Jaiswal Chinmay Jaiswal - 9 months ago 83
reST (reStructuredText) Question

Spring @PreAuthorize not working in RestController

I have GrantedAuthorities as

[admin, player, user]
To test this I have injected Authentication object in method and invoked
authentication.getAuthorities().
but when at REST Controller Method I put
@PreAuthorize("hasRole('ROLE_player')")
I am getting response for my REST web service as
403 forbidden.


I have custom roles defined which I am picking from database. I want to authorize REST call before execution of any business logic.
Tried with
@Secured
but still not working.

Answer Source

The default prefix for hasRole is ROLE_. If a prefix isn't supplied, spring will automatically add it. Since your roles in your database aren't prefixed with ROLE_ they will not match with hasRole.

// will be checking for ROLE_admin, your role in DB is admin
@PreAuthorize("hasRole('admin')") 

You can update your roles in your db to prefix them with ROLE_ or you can alter the prefix spring uses on DefaultWebSecurityExpressionHandler. You should also be able to use hasAuthority rather than hasRole. The hasAuthority will not add any prefix to the supplied parameter.

@PreAuthorize("hasAuthority('admin')") 

http://docs.spring.io/spring-security/site/docs/current/reference/html/el-access.html