Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security with Spring Boot: Allowing unauthenticated user access on specific endpoints when using a filter

I'm struggling with the basics of Spring Security here.

What I wish to achieve

My system is only for REST API handling, there's a login endpoint POST on /user/sign_in and a few open endpoints - GET on /prompt/, /prompt/{id}, /story/, /story/{id}, rest everything is for authenticated users only.


I have a custom authentication filter which I've put before the BasicAuthenticationFilter. I'm sharing my WebSecurityConfigurerAdapter code here

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DemoAuthenticationProvider demoAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers(HttpMethod.GET, "/version", "/story", "/prompt").permitAll()
                .antMatchers(HttpMethod.POST, "/user/sign_in").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(new DemoAuthenticationFilter(), BasicAuthenticationFilter.class);
        http.csrf().disable();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(demoAuthenticationProvider);
    }
}

For the anonymous user for the open endpoints, I'm returning a null authentication token in the filter and I'm getting

403 Access Denied

Why should authentication token be required when I've mentioned to permit all and not just authenticated for those end points? And how do I go about implementing it correctly?

like image 904
AA_PV Avatar asked Dec 02 '16 08:12

AA_PV


2 Answers

My bad!

End-points of spring-boot = request mapping of controller + request mapping of method. The GETs I mentioned are mapped at /. On changing to

.antMatchers(HttpMethod.GET, "/version/", "/story/", "/prompt/").permitAll()
                .antMatchers(HttpMethod.POST, "/user/sign_in/").permitAll()

things are rolling.

like image 71
AA_PV Avatar answered Sep 30 '22 14:09

AA_PV


This works for mine :

 .and().authorizeRequests().antMatchers("/URL1/**", "/URL2/**").anonymous().anyRequest().authenticated();
like image 44
Pasha GR Avatar answered Sep 30 '22 14:09

Pasha GR