[英]Can't access Spring Security /login endpoint when CSRF is enabled
I've found quite a few questions about this, but no real answers in my case.我发现了很多关于这个的问题,但在我的案例中没有真正的答案。 I am using Spring with Java on my back-end and a React front-end with Axios JS.
我在后端使用 Spring 和 Java,在 React 前端使用 Axios JS。 When trying to access the
/login
endpoint to authenticate via form login, I get a 403 response due to an invalid CSRF token.当尝试访问
/login
端点以通过表单登录进行身份验证时,由于 CSRF 令牌无效,我收到 403 响应。
Is there a way around this besides disabling CSRF for /login
?除了为
/login
禁用 CSRF 之外,还有其他方法吗? Is that considered "secure"?这被认为是“安全的”吗? It is my understanding that the server will send the CSRF token, and my front-end does not communicate with the back-end before authenticating via
/login
.据我了解,服务器将发送 CSRF 令牌,而我的前端在通过
/login
进行身份验证之前不会与后端通信。 Below are my security configuration and Axios call.以下是我的安全配置和 Axios 调用。
Thanks!谢谢!
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
CsrfTokenRepository repository = CookieCsrfTokenRepository.withHttpOnlyFalse();
Customizer<CorsConfigurer<HttpSecurity>> corsCustomizer = Customizer.withDefaults();
AuthenticationSuccessHandler successHandler = (request, response, authentication) -> {
int status = HttpStatus.OK.value();
response.setStatus(status);
};
AuthenticationFailureHandler failureHandler = (request, response, exception) -> {
int status = HttpStatus.UNAUTHORIZED.value();
response.setStatus(status);
};
Customizer<ExceptionHandlingConfigurer<HttpSecurity>> exceptionCustomizer = (configurer) -> {
HttpStatusEntryPoint entryPoint = new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
configurer.authenticationEntryPoint(entryPoint);
};
httpSecurity.csrf()
.csrfTokenRepository(repository)
.and()
.cors(corsCustomizer)
.authorizeHttpRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.successHandler(successHandler)
.failureHandler(failureHandler)
.and()
.httpBasic()
.and()
.exceptionHandling(exceptionCustomizer);
return httpSecurity.build();
} //securityFilterChain
const formData = new FormData();
formData.append("username", username);
formData.append("password", password);
const config = {
"withCredentials": true
};
const axios = require("axios").default;
return new Promise<void> ((resolve, reject) => {
axios.post("http://localhost:8080/login", formData, config)
.then((response: AxiosResponse) => {
resolve();
})
.catch(() => {
reject();
});
});
At time 0 you don't have a CSRF cookie, so you need to retrieve it.在时间 0,您没有 CSRF cookie,因此您需要检索它。 Make any GET call first and be sure to always send the token.
首先进行任何 GET 调用,并确保始终发送令牌。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.