У меня есть приложение, в интерфейсе которого используется React Remix. Он выполняет аутентификацию и создает файлы cookie сеанса, которые будут использоваться для проверки пользователя. Этот файл cookie сеанса включен в HTTP-запросы.
У нас также есть бэкэнд весенней загрузки Java, к которому мы хотим получить доступ и использовать этот же файл cookie сеанса для защиты определенных конечных точек. Я создал фильтр для проверки существования файла cookie. Если он есть, мы хотим считать пользователя аутентифицированным и можем передать запрос в нужную конечную точку.
На основе регистрируется в фильтре, он находит файл cookie и завершает работу без ошибок. Но затем ремикс получает ошибку 401, и мои журналы в конечной точке не достигаются, что указывает на то, что фильтр никогда не передал запрос.
Может ли кто-нибудь помочь? Есть ли какая-то другая фильтрация, которую будет выполнять Spring Security, которую мне нужно как-то обойти?
Вот мой фильтр и конфигурация безопасности:
package com.example.surfspotsapi.config;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Cookie;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
public class SessionCookieFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(SessionCookieFilter.class);
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
logger.info("Entering SessionCookieFilter for request: {}", httpRequest.getRequestURI());
Cookie[] cookies = httpRequest.getCookies();
boolean sessionCookieExists = false;
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("session".equals(cookie.getName())) {
sessionCookieExists = true;
logger.info("Session cookie found for request: {}", httpRequest.getRequestURI());
break;
}
}
}
if (sessionCookieExists) {
PreAuthenticatedAuthenticationToken authToken = new PreAuthenticatedAuthenticationToken("preAuthenticatedUser",
null, null);
SecurityContextHolder.getContext().setAuthentication(authToken);
logger.info("Pre-authenticated token set for request: {}", httpRequest.getRequestURI());
chain.doFilter(request, response);
} else {
logger.warn("Session cookie missing, blocking request: {}", httpRequest.getRequestURI());
httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
package com.lovettj.surfspotsapi.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SessionCookieFilter sessionCookieFilter() {
return new SessionCookieFilter();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable()) // Disable CSRF for API usage
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/user/login", "/api/user/register",
"/api/user/profile", "/api/continents/**",
"/api/countries/**", "/api/regions/**",
"/api/surf-spots/**")
.permitAll() // Public endpoints
.anyRequest().authenticated() // Protect other endpoints
)
.addFilterBefore(sessionCookieFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}```
Подробнее здесь: https://stackoverflow.com/questions/791 ... pring-boot
Невозможно вызвать защищенные конечные точки при отправке действительных файлов cookie сеанса при весенней загрузке. ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
IntelliJ Idea Идея конечные точки с переменным путем в инструменте «Конечные точки»
Anonymous » » в форуме JAVA - 0 Ответы
- 12 Просмотры
-
Последнее сообщение Anonymous
-