How to secure REST API with Spring Boot and Spring Security?

Token based authentication – users will provide its credentials and get
unique and time limited access token. I would like to manage token
creation, checking validity, expiration in my own implementation.

Actually, use Filter for token Auth – best way in this case

Eventually, you can create CRUD via Spring Data for managing Token’s properties like to expire, etc.

Here is my token filter:

And Token Service Implementation

Some REST resources will be public – no need to authenticate at all

It’s not a problem, you can manage your resources via Spring security config like this: .antMatchers("/rest/blabla/**").permitAll()

Some resources will be accessible only for users with administrator rights,

Take a look at @Secured annotation to class. Example:

@RequestMapping(value = "/adminservice")
public class AdminServiceController {

The other resource will be accessible after authorization for all users.

Back to Spring Security configure, you can configure your url like this:


I don’t want to use Basic authentication

Yep, via token filter, your users will be authenticated.

Java code configuration (not XML)

Back to the words above, look at @EnableWebSecurity.
Your class will be:

public class SecurityConfig extends WebSecurityConfigurerAdapter {}

You have to override the configure method. Code below, just for example, how to configure matchers. It’s from another project.

protected void configure(HttpSecurity http) throws Exception {
                .defaultSuccessUrl("", true)
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))

Leave a Comment