Vivek Kothari
Vivek Kothari

Reputation: 472

Setup custom auth and role in spring security

I have extended WebSecurityConfigurerAdapter to configure custom authentication and authorization. I have introduced a new API say, "/v1/api". My requirement is as follows,

  1. This API is supposed to be called by an entity with role "API_ROLE" and no one else
  2. Also a person with "API_ROLE" should not be able to call any other API in the system.

How would my configuration look like?

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/v1/api**").hasAuthority("ROLE_API");

The above code achieves the 1 purpose, how do I block person with this role to hit any other API?

Upvotes: 0

Views: 144

Answers (1)

shazin
shazin

Reputation: 21923

You can use the following Java Configuration.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/v1/api**").hasAuthority("ROLE_API")
        .and().authorizeRequests()
        .antMatchers("/**").not().hasAuthority("ROLE_API");

Upvotes: 1

Related Questions