Skip to main content

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​

  1. Complete the basic integration described in Authentication and authorization for REST APIs – Integration. Leave jeap.security.oauth2.resourceserver.system-name unset — setting it activates authorization with semantic roles instead.

  2. If the default role-to-authority mapping (prefixing each role with ROLE_) is not sufficient, provide a custom AuthoritiesResolver Spring bean — see Authorization with authorities – Integration for the API and an example implementation.

  3. Check an authority declaratively in the SpEL expressions of the @PreAuthorize and @PostAuthorize annotations using hasAuthority:

    @RestController
    public class ExampleResource {

    @GetMapping("/example")
    @PreAuthorize("hasAuthority('example:read')")
    public String hello() {
    return "Hello World";
    }
    }
  4. 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:

    @RestController
    public class ExampleResource {

    @GetMapping("/example")
    public String hello(Authentication authentication) {
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    ...
    }
    }