Для этой цели существует CookieAuthenticationFilter , UserAuthProvider и SecurityConfig:
CookieAuthenticationFilter
Код: Выделить всё
public class CookieAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
Cookie cookie = Stream.of(Optional.ofNullable(request.getCookies())
.orElse(new Cookie[0]))
.filter(entry -> "token".equals(entry.getName()))
.findFirst()
.orElse(null);
SecurityContextHolder.getContext()
.setAuthentication(new PreAuthenticatedAuthenticationToken(
cookie != null ? cookie.getValue() : "",
null));
filterChain.doFilter(request, response);
}
}
Код: Выделить всё
@Component
public class UserAuthProvider implements AuthenticationProvider {
private final AuthenticationService authenticationService;
public UserAuthProvider(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
User user = null;
if (authentication instanceof PreAuthenticatedAuthenticationToken) {
user = authenticationService.validateUser((String) authentication.getPrincipal());
}
return user != null ? new UserAuthenticationToken(user) : null;
}
@Override
public boolean supports(Class authentication) {
return true;
}
}
Код: Выделить всё
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http, UserAuthProvider userAuthProvider) throws Exception {
AuthenticationManagerBuilder builder = http.getSharedObject(AuthenticationManagerBuilder.class);
builder.authenticationProvider(userAuthProvider);
return builder.build();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity security, HttpSession session) throws Exception {
security
.csrf(customizer -> customizer.disable())
.addFilterBefore(new CookieAuthenticationFilter(), BasicAuthenticationFilter.class)
.authorizeHttpRequests(configurer -> configurer
.requestMatchers("/*").authenticated()
.anyRequest().permitAll())
.sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return security.build();
}
}
Spring Boot 3.3.1
- Что я упускаю?
- Есть ли способ разрешить переменную пути внутри фильтра?
- Хороша ли реализация аутентификации на уровне перехватчиков?
Подробнее здесь: https://stackoverflow.com/questions/790 ... ication-in
Мобильная версия