Javier
Javier

Reputation: 2095

Spring Security: Allow a public endpoint and not allow other endpoints

First of all, apologize for the grammatical errors that you can make. My English is not very good.

I'm new with Spring, and I'm trying to create a Basic Auth security.

I'm trying to configure that one endpoint has public access and others admin an user access.

This is my idea:

localhost:8080/api/teacher/findAll -> Public Access

localhost:8080/api/teacher/admin/findAll -> Only ADMIN Access

localhost:8080/api/teacher/user/findAll -> Only USER Access

Here is my code:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("user").roles("USER")
        .and().withUser("admin").password("admin").roles("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
        .antMatchers("/teacher/findAll").permitAll()
        .antMatchers("/teacher/admin/findAll").hasRole("ADMIN")
        .antMatchers("/teacher/user/findAll").hasRole("USER")
        .antMatchers("*/create/**").hasRole("ADMIN")
        .and().httpBasic();
    }

    @SuppressWarnings("deprecation")
    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}

Upvotes: 3

Views: 11279

Answers (1)

YogendraR
YogendraR

Reputation: 2386

You can try to create following End points:

1) localhost:8080/api/teacher/all/findAll -> Public Access

2) localhost:8080/api/teacher/admin/findAll -> Only ADMIN Access

3) localhost:8080/api/teacher/user/findAll -> Only USER Access

Then your configure method would like this:

 @Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests()
    .antMatchers("/teacher/all/**").permitAll()
    .antMatchers("/teacher/admin/**","*/create/**").hasRole("ADMIN")
    .antMatchers("/teacher/user/**").hasRole("USER")
    .and().httpBasic();
}

Upvotes: 2

Related Questions