Делаю приложение. Сервер Java и UI React. Уже подключил CORS, но теперь не могу настроить CSRF защиту.
Конфигурация Spring Security
:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
http
.cors().and()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
http
.rememberMe()
.key("remember-secret-key")
.rememberMeParameter("remember")
.rememberMeCookieName("REMEMBER")
.tokenValiditySeconds(REMEMBERED_SESSION_TIMEOUT)
.tokenRepository(persistentTokenRepository());
http
.formLogin()
.usernameParameter("email")
.passwordParameter("password")
.successHandler((httpServletRequest, httpServletResponse, authentication) -> {
log.info("Principal {} logged on successfully", authentication.getName());
httpServletResponse.setStatus(HttpStatus.OK.value());
})
.failureHandler((httpServletRequest, httpServletResponse, e) -> {
log.info("Login was failed");
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
});
http
.exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login") {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
if (authException != null) {
response.sendError(HttpStatus.FORBIDDEN.value());
}
}
});
http
.logout()
.invalidateHttpSession(true)
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK));
http
.authorizeRequests()
.anyRequest().authenticated();
}
Для аутентификации в React я разместил такой код:
const authRequester = axios.create({
baseURL: 'http://localhost:8080/',
withCredentials: true
});
export const profileAPI = {
login(email, password, remember = false) {
let bodyFormData = new FormData();
bodyFormData.append('email', email);
bodyFormData.append('password', password);
bodyFormData.append('remember', String(remember));
return authRequester.post('login', bodyFormData, {
headers: {
'Content-Type': 'multipart/form-data',
'X-XSRF-TOKEN': getXSRFToken()
}
});
}
}
const getXSRFToken = () => {
return Cookies.get('XSRF-TOKEN');
}
Возникает любопытный эффект. Вообще, при одном нажатии на кнопку "Вход" делается два запроса, один OPTIONS, второй POST. Так вот именно POST возвращает 403 ошибку:
Request URL: http://localhost:8080/login | Request Method: OPTIONS | Status Code: 200
Request URL: http://localhost:8080/login | Request Method: POST | Status Code: 403
После первой попытки я нажимаю "Вход" ещё раз, и картина меняется. Мало того, что запросы OPTIONS и POST начинают идти в другом порядке, так ещё и аутентификация проходит успешно. После первого запроса все остальные запросы выглядят вот так:
Request URL: http://localhost:8080/login | Request Method: POST | Status Code: 200
Request URL: http://localhost:8080/login | Request Method: OPTIONS | Status Code: 200
Во-первых я не понимаю, а почему порядок запросов меняется? Разве смысл OPTIONS не в том, чтобы идти первым и "разведывать обстановку"? Во-вторых, что мне сделать, чтобы первый запрос проходил успешно?
UPD
Запрос Options (при первой аутентификации):
**General**
Request URL: http://localhost:8080/login
Request Method: OPTIONS
Status Code: 200
Remote Address: [::1]:8080
Referrer Policy: strict-origin-when-cross-origin
**Response header**
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: x-xsrf-token
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Max-Age: 1800
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Length: 0
Date: Fri, 02 Apr 2021 14:36:29 GMT
Expires: 0
Keep-Alive: timeout=60
Pragma: no-cache
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
**Request headers**
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: x-xsrf-token
Access-Control-Request-Method: POST
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:8080
Origin: http://localhost:3000
Pragma: no-cache
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36
Запрос POST (при первой аутентификации):
**General**
Request URL: http://localhost:8080/login
Request Method: POST Status
Code: 403 Remote Address: [::1]:8080
Referrer Policy: strict-origin-when-cross-origin
**Response headers**
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:3000
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Length: 0 Date: Fri, 02 Apr 2021 14:36:29 GMT Expires: 0
Keep-Alive: timeout=60
Pragma: no-cache
Set-Cookie: XSRF-TOKEN=b09ad580-f93a-4a6e-9898-6b46099fef5b; Path=/
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
**Request headers**
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 353
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryGaSAy1p6Mp8ixURe
Host: localhost:8080
Origin: http://localhost:3000
Pragma: no-cache
Referer: http://localhost:3000/
sec-ch-ua: "Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36
X-XSRF-TOKEN: undefined