Почему Spring Security защищает URL с тем же происхождением по -разному?JAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Почему Spring Security защищает URL с тем же происхождением по -разному?

Сообщение Anonymous »

Я пытаюсь написать страницу входа в систему и регистрации, используя React. Данные из формы отправляются в/api/auth/login из формы входа в систему, а также на/API/AUTH/подписнут из регистрации. Spring Security разрешает запросы входа в систему, но не проходит запросы регистрации. Я пытался изменить конфигурацию CORS, но это не похоже на проблему. @Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.csrf(AbstractHttpConfigurer::disable)
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.authorizeHttpRequests(request -> request
.requestMatchers(HttpMethod.POST, "/api/auth/**").permitAll()
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/users/get/username/*").permitAll()
.requestMatchers(HttpMethod.GET, "/swagger-ui/**", "/api-docs/**").permitAll()
.anyRequest().authenticated())
.sessionManagement(sessionManagement -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("http://localhost:5173"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
configuration.setExposedHeaders(List.of("x-auth-token"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}

jwtauthenticationfilter
@Override
protected void doFilterInternal(
@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull FilterChain filterChain
) throws ServletException, IOException {
final String authHeader = request.getHeader("Authorization");

if (request.getRequestURI().startsWith("/api/auth/") || request.getRequestURI().startsWith("/api/users/get/username/")) {
filterChain.doFilter(request, response);
return;
}

if (authHeader == null || !authHeader.startsWith("Bearer ")) {
log.error("There is no authentication token or header!");
filterChain.doFilter(request, response);
}

try {
final String jwt = authHeader.substring(7);
final String username = jwtService.extractUsername(jwt);

if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

User user = (User) this.userService.loadUserByUsername(username);

if (jwtService.isTokenValid(jwt, user)) {
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
user,
null,
user.getAuthorities()
);

authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authToken);
} else {
log.error("Invalid subject!");
response.setStatus(401);
}
}

filterChain.doFilter(request, response);
} catch (Exception exception) {
handlerExceptionResolver.resolveException(request, response, null, exception);
}
}

authcontroller
@PostMapping("/signup")
@Operation(summary = "Registration", description = "Allows user to create new account.")
@ApiResponses(
value = {
@ApiResponse(responseCode = "201", description = "Registered successfully!"),
@ApiResponse(responseCode = "400", description = "Entered data not valid.")
}
)
public ResponseEntity signup(@Valid @RequestBody SignUpRequest user) throws UniqueConstraintException {
log.info("Signing up user with username: '{}' and phone number: '{}'", user.getUsername(), user.getPhoneNumber());
authenticationService.signup(user);
log.info("User username: '{}' and phone number: '{}' successfully signed in!", user.getUsername(), user.getPhoneNumber());
return ResponseEntity.status(201).build();
}

@PostMapping("/login")
@Operation(summary = "Log In", description = "Allows user to login.")
@ApiResponses(
value = {
@ApiResponse(responseCode = "200", description = "Logged in successfully!"),
@ApiResponse(responseCode = "404", description = "User with such username or phone number not found!")
}
)
public ResponseEntity login(@Valid @RequestBody LoginRequest user) throws UserNotFoundException {
log.info("Trying to log in user with username: '{}' and phone number: '{}'", user.getUsername(), user.getPhoneNumber());
User loginUser = authenticationService.login(user);
String token = jwtService.generateToken(loginUser);
LoginResponse loginResponse = new LoginResponse(token, jwtService.getJwtExpiration());
log.info("User with username: '{}' and phone number: '{}' logged in successfully!", user.getUsername(), user.getPhoneNumber());

return ResponseEntity.ok(loginResponse);
}

frontend
Authapi
import axios from "axios";

export async function login(username, phoneNumber, password) {
console.log(username, phoneNumber, password);
const { token } = await axios.post(
"http://localhost:8080/api/auth/login",
{
username,
phoneNumber,
password,
},
{
headers: {
"Content-Type": "application/json",
},
}
);
return token;
}
export async function signup(username, phoneNumber, password, balance) {
console.log(username, phoneNumber, password);
const response = await axios
.post(
"http://localhost:8080/api/auth/signup",
{
username,
phoneNumber,
password,
balance,
},
{
headers: {
"Content-Type": "application/json",
},
}
)
.then((response) => console.log(response));
console.log(response);
return response;
}

logs
2025-06-10T17:45:35.898+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected DefaultRequestToViewNameTranslator
2025-06-10T17:45:35.898+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'beanNameViewResolver'
2025-06-10T17:45:35.898+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'mvcViewResolver'
2025-06-10T17:45:35.898+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'defaultViewResolver'
2025-06-10T17:45:35.898+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'viewResolver'
2025-06-10T17:45:35.898+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'thymeleafViewResolver'
2025-06-10T17:45:35.898+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'flashMapManager'
2025-06-10T17:45:35.898+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected SessionFlashMapManager
2025-06-10T17:45:35.898+03:00 DEBUG 35282 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='true': request parameters and headers will be shown which may lead to unsafe logging of potentially sensitive data
2025-06-10T17:45:35.898+03:00 INFO 35282 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2025-06-10T17:45:35.902+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.b.w.s.f.OrderedRequestContextFilter : Bound request context to thread: org.apache.catalina.connector.RequestFacade@6947beb8
2025-06-10T17:45:35.902+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'springSecurityFilterChain'
2025-06-10T17:45:35.909+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'authenticationRestController'
2025-06-10T17:45:35.910+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Trying to match request against DefaultSecurityFilterChain defined as 'securityFilterChain' in [class path resource [com/epam/finaltask/config/SecurityConfig.class]] matching [any request] and having filters [DisableEncodeUrl, WebAsyncManagerIntegration, SecurityContextHolder, HeaderWriter, Cors, Logout, JwtAuthentication, RequestCacheAware, SecurityContextHolderAwareRequest, AnonymousAuthentication, SessionManagement, ExceptionTranslation, Authorization] (1/1)
2025-06-10T17:45:35.911+03:00 DEBUG 35282 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Securing OPTIONS /api/auth/signup
2025-06-10T17:45:35.911+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking DisableEncodeUrlFilter (1/13)
2025-06-10T17:45:35.911+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking WebAsyncManagerIntegrationFilter (2/13)
2025-06-10T17:45:35.912+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking SecurityContextHolderFilter (3/13)
2025-06-10T17:45:35.912+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking HeaderWriterFilter (4/13)
2025-06-10T17:45:35.913+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Invoking CorsFilter (5/13)
2025-06-10T17:45:35.924+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match request to [Is Secure]
2025-06-10T17:45:35.924+03:00 TRACE 35282 --- [nio-8080-exec-1] o.s.b.w.s.f.OrderedRequestContextFilter : Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@6947beb8


Подробнее здесь: https://stackoverflow.com/questions/796 ... ifferently
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

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