How to: authorize REST API access with authorities
Authorities let an application check fine-grained, application-local permissions derived from a user's roles, using Spring Security's own authority mechanism.
Steps
-
Complete the basic integration described in Authentication and authorization for REST APIs – Integration. Leave
jeap.security.oauth2.resourceserver.system-nameunset — setting it activates authorization with semantic roles instead. -
If the default role-to-authority mapping (prefixing each role with
ROLE_) is not sufficient, provide a customAuthoritiesResolverSpring bean — see Authorization with authorities – Integration for the API and an example implementation. -
Check an authority declaratively in the SpEL expressions of the
@PreAuthorizeand@PostAuthorizeannotations usinghasAuthority:@RestControllerpublic class ExampleResource {@GetMapping("/example")@PreAuthorize("hasAuthority('example:read')")public String hello() {return "Hello World";}} -
Or, to query the actual authorities of a user — for example to search a database for objects matching these permissions — obtain them from the Spring Security
Authentication:@RestControllerpublic class ExampleResource {@GetMapping("/example")public String hello(Authentication authentication) {Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();...}}
Related
- Authorization with authorities — the
AuthoritiesResolverAPI reference and a complete example. - Role concept in the Blueprint Microservice — understand simple roles, semantic roles and authorities before choosing one.
- How to: authorize REST API access with roles — the alternative models based on roles carried in the token.
- Authentication and authorization for REST APIs — the basic integration these steps build on.