Using spring security with jwt.
My spring security config:
@RequiredArgsConstructor
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final JwtFilter jwtFilter;
private final exceptionHandler exceptionHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/v1/users/**").hasAnyRole("USER")
.antMatchers("/api/v1/admin/**").hasRole("ADMIN")
.anyRequest()
.authenticated()
.and()
.addFilterBefore(jwtFilter, FilterSecurityInterceptor.class)
.exceptionHandling().authenticationEntryPoint(exceptionHandler);
}
}
When I send GET Request everything is fine. But when I send POST:
org.springframework.security.authentication.InsufficientAuthenticationException: Full authentication is required to access this resource
If i add .csrf().disable()
it will help, but i don't understand how it works. Why is Get request OK but post without .csrf().disable()
throwing an exception?
Can i pass POST requests without .csrf().disable()
part?
CodePudding user response:
To protect MVC applications, Spring adds a CSRF token to each generated view. This token must be submitted to the server on every HTTP request that modifies state (PATCH, POST, PUT and DELETE — not GET).
This protects our application against CSRF attacks since an attacker can't get this token from their own page.
for more information: https://www.baeldung.com/spring-security-csrf