Ivan
Ivan

Reputation: 49

How to designate public endpoints using custom annotation in spring rest controllers?

We are using OAuth2 for securing our REST endpoints. Nearly all of our endpoints require authentication. We have couple of public endpoints. We configure spring security using @EnableWebSecurity. All the public endpoints are explicitly listed in the configuration (see "publicpath_x" in the example below). Instead of explicitly adding each new public enpodint in the configuration, it would be much easier to have a custom annotation, e.g. @PublicAccess which will designate each public endpoint. Is it possible to configure that endpoints annotated with this annotation will be considered as public, i.e. no authentication will be required? We don't want to designate public endpoints in path (e.g. all public endpoints path will start/end with "/public").

Security configuration:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

//...

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatchers("publicpath1", "publicpath2").permitAll() //...
    }
}

Example public REST controller with custom annotation:

@RestController    
public class PublicController1 {

    @PublicAccess //our custom annotation
    @RequestMapping(value = "publicpath1", method = RequestMethod.GET)
    public void publicEndpoint1() { 
        //... 
    }
}

I was trying the following classes with no success.

javax.servlet.Filter 
org.springframework.web.servlet.handler.HandlerInterceptorAdapter

Upvotes: 1

Views: 1509

Answers (1)

Chao Luo
Chao Luo

Reputation: 2696

You can use the @PreAuthorize Annotations as method security

Detail see here

Upvotes: 2

Related Questions