важные зависимости :
Код: Выделить всё
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);
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... pring-boot
Мобильная версия