Почему Spring Security отвечает на все мои запросы кодом 403, запрещенным?JAVA

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

Сообщение Anonymous »

По какой-то причине у меня возникли проблемы с Spring Security. Я искал несколько часов, но ничего не нашел. Короче говоря, на все мои запросы отвечает запрещенный ответ 403. Я пытаюсь реализовать аутентификацию на основе JWT, но, похоже, она не работает. Что-то не так с моей конфигурацией безопасности, потому что если я не отмечу ее как конфигурацию и не воспользуюсь аннотацией Enablewebsecurity, то (например) я смогу увидеть базовую страницу входа в localhost:8080. Иначе я не могу. В некоторых сообщениях говорится, что мне следует отключить CSRF, но это не помогло.
Кроме того, я просто не могу связать два пользовательских фильтра друг с другом. Я хотел, чтобы фильтр JWTGenerator запускался перед моим JWTAuthenticationFilter, который будет запускаться до BasicAuthenticationFIlter, но если я укажу эти настройки в конфигурации, это выдаст исключение.
Я благодарен за любые совет, потому что у меня не осталось никаких идей, и я совершенно ничего не знаю.
SpringSecurityConfiguration:

Код: Выделить всё

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

private final SecurityUtil securityUtil;

public SecurityConfiguration(SecurityUtil securityUtil) {
this.securityUtil = securityUtil;
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.cors(corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() {
@Override
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Collections.singletonList("http://localhost:4200"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setAllowCredentials(true);
config.setAllowedHeaders(Collections.singletonList("*"));
config.setExposedHeaders(Arrays.asList("Authorization"));
config.setMaxAge(3600L);
return config;
}
})).csrf().disable()
.addFilterAfter(new JWTGeneratorFilter(securityUtil), BasicAuthenticationFilter.class)
.addFilterBefore(new JWTAuthenticationFilter(), BasicAuthenticationFilter.class)
.authorizeHttpRequests((requests) -> requests
.requestMatchers(HttpMethod.POST, "/login").permitAll()
.anyRequest().authenticated())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

return http.build();
}

@Bean
public AuthenticationProvider authenticationProvider(){
CustomAuthenticationProvider authenticationProvider = new CustomAuthenticationProvider();
return authenticationProvider;
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
}
JWTGeneratorFilter:

Код: Выделить всё

@RequiredArgsConstructor
@Component
public class JWTGeneratorFilter extends OncePerRequestFilter {

private final SecurityUtil securityUtil;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (null == authentication) {
ObjectMapper mapper = new ObjectMapper();
CredentialsDTO credentialsDTO = mapper.readValue(request.getInputStream(), CredentialsDTO.class);
User user = securityUtil.findByCredentialsDTO(credentialsDTO);
SecretKey key = Keys.hmacShaKeyFor(ConstantStore.JWT_SECRET.getBytes(StandardCharsets.UTF_8));
String jwt = Jwts.builder().setIssuer("FPE-Weblap").setSubject("JWT")
.claim("username", user.getUsername())
.claim("authorities", populateAuthorities(user.getRoles()))
.setIssuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + 30000000))
.signWith(key).compact();
response.setHeader(ConstantStore.TOKEN_HEADER, jwt);
request.setAttribute(ConstantStore.TOKEN_HEADER, jwt);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getRoles()));
}

filterChain.doFilter(request, response);
}

private String populateAuthorities(Collection

Подробнее здесь: [url]https://stackoverflow.com/questions/76428098/why-does-spring-security-respond-with-403-forbidden-to-all-my-requests[/url]
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

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

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