Я новичок в Java, мы внедрили проверку токена CSRF для защищенных маршрутов, даже токен соответствует его значению 403, пожалуйста, проверьте код ниже.
У меня есть /api/auth/send-otp, я отправлю otp на электронную почту адрес и /verify проверят otp, и если он действителен, вернет access_token, и при попытке получить токен обновления с помощью пост-вызова /token на этот раз мы получаем 403 ошибка.
package com.example.authentication.config;
import java.util.Arrays;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseCookie;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import com.example.authentication.filter.CsrfCookieFilter;
import java.util.function.Consumer;
import jakarta.servlet.http.Cookie;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf((csrf) -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers("/api/auth/send-otp", "/api/auth/verify-otp")
)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/send-otp", "/api/auth/verify-otp", "/error").permitAll()
.requestMatchers("/api/auth/**").permitAll()
// .requestMatchers("/api/auth/**").authenticated()
.anyRequest().authenticated()
)
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.addFilterAfter(new CsrfCookieFilter(), CsrfFilter.class); // Add custom CSRF filter
return http.build();
}
@Bean
public CookieCsrfTokenRepository cookieCsrfTokenRepository() {
CookieCsrfTokenRepository repository = CookieCsrfTokenRepository.withHttpOnlyFalse();
repository.setCookieCustomizer(cookieCustomizer());
repository.setCookieName("XSRF-TOKEN"); // Default cookie name for CSRF token
return repository;
}
private Consumer cookieCustomizer() {
return cookie -> {
cookie.secure(false); // Ensure the cookie is only sent over HTTPS
cookie.httpOnly(false); // Prevent JavaScript access to the cookie
cookie.path("/"); // Make the cookie available application-wide
cookie.sameSite("None");
};
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:2345"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization", "X-Requested-With"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... ted-routes
Проверка токена CSRF всегда выдает 403 для защищенных маршрутов ⇐ JAVA
Программисты JAVA общаются здесь
-
Anonymous
1736528046
Anonymous
Я новичок в Java, мы внедрили проверку токена CSRF для защищенных маршрутов, даже токен соответствует его значению 403, пожалуйста, проверьте код ниже.
У меня есть /api/auth/send-otp, я отправлю otp на электронную почту адрес и /verify проверят otp, и если он действителен, вернет access_token, и при попытке получить токен обновления с помощью пост-вызова /token на этот раз мы получаем 403 ошибка.
package com.example.authentication.config;
import java.util.Arrays;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseCookie;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import com.example.authentication.filter.CsrfCookieFilter;
import java.util.function.Consumer;
import jakarta.servlet.http.Cookie;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf((csrf) -> csrf
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers("/api/auth/send-otp", "/api/auth/verify-otp")
)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/send-otp", "/api/auth/verify-otp", "/error").permitAll()
.requestMatchers("/api/auth/**").permitAll()
// .requestMatchers("/api/auth/**").authenticated()
.anyRequest().authenticated()
)
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.addFilterAfter(new CsrfCookieFilter(), CsrfFilter.class); // Add custom CSRF filter
return http.build();
}
@Bean
public CookieCsrfTokenRepository cookieCsrfTokenRepository() {
CookieCsrfTokenRepository repository = CookieCsrfTokenRepository.withHttpOnlyFalse();
repository.setCookieCustomizer(cookieCustomizer());
repository.setCookieName("XSRF-TOKEN"); // Default cookie name for CSRF token
return repository;
}
private Consumer cookieCustomizer() {
return cookie -> {
cookie.secure(false); // Ensure the cookie is only sent over HTTPS
cookie.httpOnly(false); // Prevent JavaScript access to the cookie
cookie.path("/"); // Make the cookie available application-wide
cookie.sameSite("None");
};
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:2345"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization", "X-Requested-With"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79346436/csrf-token-validation-alway-giving-403-for-protected-routes[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия