How to make a particular API public and rest private (needs authentication) in springboot

61 views Asked by At

I have 3 API endpoints all having GET, POST & DELETE functions, 3 are secured using spring boot security,

  1. /api/travel
  2. /api/employees
  3. /api/assoc

I want /api/employees's POST to be publicly accessible, because it's my Sign-up logic as obviously the user doesn't have to sign in to sign up.

Below is the Config file's filter snipppet thats not working:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity security) throws Exception{
        return security.csrf(csrf->csrf.disable())
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers(HttpMethod.POST, "/api/employees").permitAll()
                        .anyRequest().authenticated()
                )
                .httpBasic(Customizer.withDefaults())
                .build();
    }

I

I tried POSTing the body as Json in Postman to /api/employees with no authorisation header, but it is giving me 401 unauthorised.

1

There are 1 answers

0
Mateusz On

Try option with extends YOUR_CLASS with WebSecurityConfigurerAdapter, after that override method

protected void configure(HttpSecurity http) throws Exception {}

in this method you can put your code inside, remeber YOUR_CLASS should be annotated with:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class YOUR_CLASS