Файл cookie сеанса не сохраняется в браузере – Spring BootJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Файл cookie сеанса не сохраняется в браузере – Spring Boot

Сообщение 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 создает нулевую аутентификацию. Я также попробовал это с почтальоном, и там все работает как положено.

Подробнее здесь: https://stackoverflow.com/questions/791 ... pring-boot
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»