Я создаю учетную запись с помощью Spring Boot, но, видимо, управление моим сеансом не работает должным образом, поскольку сеанс не сохраняется в браузере, даже несмотря на то, что он отправляет ответ.
важные зависимости :
org.springframework.boot
spring-boot-starter-security
org.springframework.session
spring-session-jdbc
файл конфигурации:
@Configuration(proxyBeanMethods = false)
@EnableJdbcHttpSession
@EnableWebSecurity
public class SecurityConfig {
private CustomAuthenticationFilter customAuthenticationFilter;
public SecurityConfig(CustomAuthenticationFilter customAuthenticationFilter){
this.customAuthenticationFilter = customAuthenticationFilter;
}
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
RequestCache nullRequestCache = new NullRequestCache();
return http
.addFilterAt(customAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.csrf(csrf -> csrf
.disable()
)
.cors(cors -> cors
.configurationSource(corsConfigurationSource())
)
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(PermittedEndpoints.list).permitAll()
.anyRequest().authenticated()
)
.requestCache(cache -> cache
.requestCache(nullRequestCache)
)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.maximumSessions(1)
.maxSessionsPreventsLogin(true)
)
.securityContext((securityContext) -> securityContext
.securityContextRepository(securityContextRepository()))
.build();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:5173"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
SecurityContextRepository securityContextRepository() {
return new DelegatingSecurityContextRepository(
new RequestAttributeSecurityContextRepository(),
new HttpSessionSecurityContextRepository()
);
}
@Bean
CookieSerializer cookieSerializer() {
DefaultCookieSerializer serializer = new DefaultCookieSerializer();
serializer.setCookieName("JSESSIONID");
serializer.setCookiePath("/");
serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
serializer.setUseHttpOnlyCookie(true);
serializer.setSameSite("Lax");
serializer.setUseSecureCookie(true);
return serializer;
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
}
Идея состоит в том, что неаутентифицированный пользователь перенаправляется на страницу входа при доступе к странице, требующей аутентификации. Это работает нормально, но когда я пытаюсь зарегистрироваться (сохранить контекст в SecurityContextRepository) и получить доступ к аутентифицированной конечной точке, я все равно перенаправляюсь на страницу входа, потому что сеанс не возвращается, а Spring создает нулевую аутентификацию. Я также попробовал это с почтальоном, и там он работает так, как ожидалось.
ОБНОВЛЕНИЕ
Я не предоставил свой код внешнего интерфейса, но ошибка была. Для своих запросов я использую Javascript Fetch API в React, который выглядит следующим образом:
useEffect(() => {
async function authenticate(){
const response = await fetch(`http://localhost:8080/authenticate?${"u"}=${location}`, {
method: "GET",
headers:{
"Accept": "application/json",
"credentials": "include"
}
})
if(!response.ok){
throw new Error("Request failed");
}
const json = await response.json()
setIsAuthenticated(json.value)
if(json.value == "false"){
navigate("/login")
}
}
authenticate()
}, [location, navigate])
Я думал, что «credentials»: «include» — это заголовок, но это часть Fetch API, поэтому мне просто пришлось убрать эту строку из заголовка, чтобы все исправить. :
useEffect(() => {
async function authenticate(){
const response = await fetch(`http://localhost:8080/authenticate?${"u"}=${location}`, {
method: "GET",
headers:{
"Accept": "application/json"
},
credentials: "include"
})
if(!response.ok){
throw new Error("Request failed");
}
const json = await response.json()
setIsAuthenticated(json.value)
if(json.value == "false"){
navigate("/login")
}
}
authenticate()
}, [location, navigate])
Подробнее здесь: https://stackoverflow.com/questions/791 ... pring-boot
Файл cookie сеанса не сохраняется в браузере – Spring Boot ⇐ JAVA
Программисты JAVA общаются здесь
-
Anonymous
1730468886
Anonymous
Я создаю учетную запись с помощью Spring Boot, но, видимо, управление моим сеансом не работает должным образом, поскольку сеанс не сохраняется в браузере, даже несмотря на то, что он отправляет ответ.
важные зависимости :
org.springframework.boot
spring-boot-starter-security
org.springframework.session
spring-session-jdbc
файл конфигурации:
@Configuration(proxyBeanMethods = false)
@EnableJdbcHttpSession
@EnableWebSecurity
public class SecurityConfig {
private CustomAuthenticationFilter customAuthenticationFilter;
public SecurityConfig(CustomAuthenticationFilter customAuthenticationFilter){
this.customAuthenticationFilter = customAuthenticationFilter;
}
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
RequestCache nullRequestCache = new NullRequestCache();
return http
.addFilterAt(customAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.csrf(csrf -> csrf
.disable()
)
.cors(cors -> cors
.configurationSource(corsConfigurationSource())
)
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(PermittedEndpoints.list).permitAll()
.anyRequest().authenticated()
)
.requestCache(cache -> cache
.requestCache(nullRequestCache)
)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.maximumSessions(1)
.maxSessionsPreventsLogin(true)
)
.securityContext((securityContext) -> securityContext
.securityContextRepository(securityContextRepository()))
.build();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:5173"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
SecurityContextRepository securityContextRepository() {
return new DelegatingSecurityContextRepository(
new RequestAttributeSecurityContextRepository(),
new HttpSessionSecurityContextRepository()
);
}
@Bean
CookieSerializer cookieSerializer() {
DefaultCookieSerializer serializer = new DefaultCookieSerializer();
serializer.setCookieName("JSESSIONID");
serializer.setCookiePath("/");
serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
serializer.setUseHttpOnlyCookie(true);
serializer.setSameSite("Lax");
serializer.setUseSecureCookie(true);
return serializer;
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
}
Идея состоит в том, что неаутентифицированный пользователь перенаправляется на страницу входа при доступе к странице, требующей аутентификации. Это работает нормально, но когда я пытаюсь зарегистрироваться (сохранить контекст в SecurityContextRepository) и получить доступ к аутентифицированной конечной точке, я все равно перенаправляюсь на страницу входа, потому что сеанс не возвращается, а Spring создает нулевую аутентификацию. Я также попробовал это с почтальоном, и там он работает так, как ожидалось.
ОБНОВЛЕНИЕ
Я не предоставил свой код внешнего интерфейса, но ошибка была. Для своих запросов я использую Javascript Fetch API в React, который выглядит следующим образом:
useEffect(() => {
async function authenticate(){
const response = await fetch(`http://localhost:8080/authenticate?${"u"}=${location}`, {
method: "GET",
headers:{
"Accept": "application/json",
"credentials": "include"
}
})
if(!response.ok){
throw new Error("Request failed");
}
const json = await response.json()
setIsAuthenticated(json.value)
if(json.value == "false"){
navigate("/login")
}
}
authenticate()
}, [location, navigate])
Я думал, что «credentials»: «include» — это заголовок, но это часть Fetch API, поэтому мне просто пришлось убрать эту строку из заголовка, чтобы все исправить. :
useEffect(() => {
async function authenticate(){
const response = await fetch(`http://localhost:8080/authenticate?${"u"}=${location}`, {
method: "GET",
headers:{
"Accept": "application/json"
},
credentials: "include"
})
if(!response.ok){
throw new Error("Request failed");
}
const json = await response.json()
setIsAuthenticated(json.value)
if(json.value == "false"){
navigate("/login")
}
}
authenticate()
}, [location, navigate])
Подробнее здесь: [url]https://stackoverflow.com/questions/79135995/session-cookie-is-not-stored-in-the-browser-spring-boot[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия