Search code examples
javaspringspring-bootauthenticationspring-security

Spring Security returns login page despite permitAll


I know there is a lot of questions like this, but I could not find an answer which solves my case.

Here is my config:

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(HttpMethod.POST, "/").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .permitAll()
                .and()
            .logout().permitAll();
    }
}

And here is my endpoint I want users to have access without logging in:

@Slf4j
@RestController
public class MyController {

    @PostMapping(value = "/", consumes = MediaType.TEXT_PLAIN_VALUE)
    public void acceptAnonymously(HttpEntity<String> requestEntity) {
        log.debug("body: {}", requestEntity.getBody());
    }

}

So basically, I want to allow making unauthenticated POST requests to localhost:8080. Everything else should be authenticated. But when I hit localhost:8080 with postman, this is what I get: enter image description here


Solution

  • So, CSRF stands for Cross-Site Request Forgery and I believe is enabled by default with Spring Web/Security. When it is enabled, you need to properly pass the correct csrf token to your app in order to access your application otherwise you will get thrown a 403 forbidden type error. Alternatively, there are other means of authenticating users if you so desired.

    .csrf().disable()