Почему Spring Security отклоняет вызов из моего интерфейса?JAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Почему Spring Security отклоняет вызов из моего интерфейса?

Сообщение Anonymous »

Я создаю полнофункциональное приложение для своего TFC, используя Java с Spring Boot для серверной части и Angular для внешней части. Однако при выполнении запросов GET система безопасности Spring Boot отклоняет мои запросы.
Вот журналы безопасности Spring Boot, которые я получаю:
2024-12-22T01:55:45.750+01:00 DEBUG 2956 --- [nio-8080-exec-9] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2024-12-22T01:55:45.801+01:00 DEBUG 2956 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : Securing OPTIONS /park/status
2024-12-22T01:55:45.807+01:00 DEBUG 2956 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Securing GET /park/status
2024-12-22T01:55:45.810+01:00 DEBUG 2956 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : Securing OPTIONS /park/emergencies
2024-12-22T01:55:45.815+01:00 DEBUG 2956 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : Securing GET /park/emergencies
2024-12-22T01:55:45.819+01:00 DEBUG 2956 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : Securing OPTIONS /park/dinosaurs
2024-12-22T01:55:45.831+01:00 DEBUG 2956 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Securing OPTIONS /park/enclosures
2024-12-22T01:55:45.864+01:00 DEBUG 2956 --- [nio-8080-exec-6] o.s.security.web.FilterChainProxy : Securing GET /park/dinosaurs
2024-12-22T01:55:45.864+01:00 DEBUG 2956 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : Securing GET /park/enclosures
2024-12-22T01:55:45.918+01:00 DEBUG 2956 --- [nio-8080-exec-6] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2024-12-22T01:55:45.919+01:00 DEBUG 2956 --- [nio-8080-exec-6] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access
2024-12-22T01:55:45.919+01:00 DEBUG 2956 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2024-12-22T01:55:45.919+01:00 DEBUG 2956 --- [nio-8080-exec-7] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2024-12-22T01:55:45.920+01:00 DEBUG 2956 --- [nio-8080-exec-7] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access
2024-12-22T01:55:45.918+01:00 DEBUG 2956 --- [nio-8080-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2024-12-22T01:55:45.920+01:00 DEBUG 2956 --- [nio-8080-exec-3] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access
2024-12-22T01:55:45.920+01:00 DEBUG 2956 --- [nio-8080-exec-1] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access
2024-12-22T01:55:45.920+01:00 DEBUG 2956 --- [nio-8080-exec-6] o.s.security.web.FilterChainProxy : Securing GET /error
2024-12-22T01:55:45.921+01:00 DEBUG 2956 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : Securing GET /error
2024-12-22T01:55:45.921+01:00 DEBUG 2956 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Securing GET /error
2024-12-22T01:55:45.921+01:00 DEBUG 2956 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : Securing GET /error
2024-12-22T01:55:45.922+01:00 DEBUG 2956 --- [nio-8080-exec-6] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2024-12-22T01:55:45.922+01:00 DEBUG 2956 --- [nio-8080-exec-6] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access
2024-12-22T01:55:45.922+01:00 DEBUG 2956 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2024-12-22T01:55:45.923+01:00 DEBUG 2956 --- [nio-8080-exec-7] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2024-12-22T01:55:45.923+01:00 DEBUG 2956 --- [nio-8080-exec-3] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access
2024-12-22T01:55:45.923+01:00 DEBUG 2956 --- [nio-8080-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2024-12-22T01:55:45.923+01:00 DEBUG 2956 --- [nio-8080-exec-7] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access
2024-12-22T01:55:45.923+01:00 DEBUG 2956 --- [nio-8080-exec-1] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access
2024-12-22T01:55:51.769+01:00 DEBUG 2956 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : Securing OPTIONS /park/update
2024-12-22T01:55:51.773+01:00 DEBUG 2956 --- [nio-8080-exec-6] o.s.security.web.FilterChainProxy : Securing PUT /park/update
2024-12-22T01:55:51.775+01:00 DEBUG 2956 --- [nio-8080-exec-6] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2024-12-22T01:55:51.775+01:00 DEBUG 2956 --- [nio-8080-exec-6] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access
2024-12-22T01:55:51.776+01:00 DEBUG 2956 --- [nio-8080-exec-6] o.s.security.web.FilterChainProxy : Securing PUT /error
2024-12-22T01:55:51.777+01:00 DEBUG 2956 --- [nio-8080-exec-6] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2024-12-22T01:55:51.777+01:00 DEBUG 2956 --- [nio-8080-exec-6] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access

Я сравнил два токена, внешний и внутренний, и они одинаковы, поэтому я не знаю, почему они отклоняют мои запросы.
Это класс, в котором Я настраиваю CORS:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
private final JwtFilter jwtFilter;

@Autowired
public SecurityConfig(JwtFilter jwtFilter){
this.jwtFilter=jwtFilter;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/register", "/auth/login").permitAll()
.anyRequest().authenticated()
)
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);

return http.build();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("http://localhost:4200"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(List.of("*"));
configuration.setExposedHeaders(List.of("Authorization"));
configuration.setMaxAge(3600L);
configuration.setAllowCredentials(true);

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}

Это JwtFilter:
@Component
public class JwtFilter implements Filter {

private final JwtUtil jwtUtil;

@Autowired
public JwtFilter(JwtUtil jwtUtil){
this.jwtUtil=jwtUtil;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String authHeader = httpRequest.getHeader("Authorization");
// System.out.println(authHeader+" solicitud desde el fornted");

if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
try {
String userId=jwtUtil.validateToken(token);
httpRequest.setAttribute("userId",userId);
System.out.println("Token válido. UserId extraído: " + userId+" token "+authHeader);
} catch (Exception e) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
// System.out.println("Error al validar el token de jwt filter " + e.getMessage()+ " "+token);
httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token inválido");
return;
}
}

chain.doFilter(request, response);
}

И это класс, который я использую для генерации токена
@Component
public class JwtUtil {

@Value("${jwtKey}")
private String secretKey;

@Value("${jwtKeyExpiration}")
private long keyExpiration;

private Key key;

@PostConstruct
public void init() {
key = Keys.hmacShaKeyFor(secretKey.getBytes());
}
//genero un token con enlazado con el id del usuario mi key, que durara una 1 hora(despues el usuario
//Tendra que iniciar sesion de nuevo
public String generateToken(String userId) {
Map claims = new HashMap();
return Jwts.builder()
.claims(claims)
.subject(userId)
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + keyExpiration))
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}

public String validateToken(String token) {
Claims claims = Jwts.parser()
.setSigningKey(key)
.build()
.parseSignedClaims(token)
.getPayload();
return claims.getSubject();
}
}

Что я могу сделать, чтобы исправить ошибки 403 CORS?
Сначала я сравнил токены и определил, правильно ли серверная часть отправила их во внешний интерфейс на войдите в систему, и было ли оно таким же.
Я также просмотрел другие сообщения на этом сайте об ошибке безопасности, и у меня это не сработало.
Ошибка CORS я получаю следующее:
URL de solicitud: http://localhost:8080/park/dinosaurs
Método de la solicitud: GET
Código de estado: 403 Forbidden
Dirección remota: [::1]:8080
Política de referencia: strict-origin-when-cross-origin
access-control-allow-credentials: true
access-control-allow-methods: PUT, GET, HEAD, POST, DELETE, OPTIONS
access-control-allow-origin: http://localhost:4200
access-control-expose-headers: Authorization
cache-control: no-cache, no-store, max-age=0, must-revalidate
connection: keep-alive
content-length: 0
date: Sun, 22 Dec 2024 00:55:45 GMT
expires: 0
keep-alive: timeout=60
pragma: no-cache
vary: Origin
vary: Access-Control-Request-Method
vary: Access-Control-Request-Headers
x-content-type-options: nosniff
x-frame-options: DENY
x-xss-protection: 0
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br, zstd
accept-language: es-ES,es;q=0.9,en;q=0.8
authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwiaWF0IjoxNzM0ODI4OTQ1LCJleHAiOjE3MzQ4MzI1NDV9.Z67bJMCahmXdj9Wyq7dklPtQ0pueemMtqLjP1Ex6idw
connection: keep-alive
cookie: JSESSIONID=67222A4072B0BE13CFFA59F639C2BC02
dnt: 1
host: localhost:8080
origin: http://localhost:4200
referer: http://localhost:4200/
sec-ch-ua: "Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36


Подробнее здесь: https://stackoverflow.com/questions/793 ... y-frontend
Ответить

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

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

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

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

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