Я использую Spring Boot 3 и Spring Security 6, и когда я пытаюсь авторизовать роли, я получаю 401 неавторизовано, хотя я уверен, что у него есть необходимые полномочия, роли в базе данных такие, как ROLE_ADMIN< /em> и имеет отношения «многие-к-может» с пользователями, вот моя конфигурация безопасности, я разрешаю две цепочки фильтров безопасности: одну для регистрации и входа в систему, другую для остальных, первая использует базовую аутентификацию, а вторая использует jwt
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
private final RsaKeyProperties jwtConfigProperties;
private final JpaUserDetailsService userDetailsService;
public SecurityConfig(RsaKeyProperties jwtConfigProperties, JpaUserDetailsService userDetailsService) {
this.jwtConfigProperties = jwtConfigProperties;
this.userDetailsService = userDetailsService;
}
@Bean
@Order(1) // Highest priority to make sure this applies to /login
SecurityFilterChain basicAuthFilterChain(HttpSecurity http) throws Exception {
return http
.securityMatcher("/login") // Apply this filter chain only to /login
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error/**").permitAll()
.anyRequest().authenticated() // Require authentication for /login
)
.csrf(csrf -> csrf.disable())
.userDetailsService(userDetailsService)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(withDefaults()) // Use Basic Authentication for /login
.build();
}
// Security configuration for all other endpoints using JWT Authentication
@Bean
@Order(2) // Lower priority than the first filter chain
SecurityFilterChain jwtAuthFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/register/**" , "/error/**").permitAll() // Allow unauthenticated access to /register
.anyRequest().authenticated() // All other requests require JWT authentication
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.headers(headers -> headers.frameOptions().sameOrigin())
.userDetailsService(userDetailsService)
.oauth2ResourceServer(oauth2 -> oauth2.jwt()) // Enable JWT Authentication
.exceptionHandling(ex -> {
ex.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint()); // Entry point for invalid tokens
ex.accessDeniedHandler(new BearerTokenAccessDeniedHandler()); // Handle access denied errors
})
.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(jwtConfigProperties.publicKey()).build();
}
@Bean
JwtEncoder jwtEncoder() {
JWK jwk = new RSAKey.Builder(jwtConfigProperties.publicKey()).privateKey(jwtConfigProperties.privateKey()).build();
JWKSource jwks = new ImmutableJWKSet(new JWKSet(jwk));
return new NimbusJwtEncoder(jwks);
}
}
JpaUserDetailsService:
@Service
public class JpaUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
public JpaUserDetailsService(UserRepository userRepository ) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepository
.findByUsername(username)
.map(UserDetailsImpl::new)
.orElseThrow(() -> new UsernameNotFoundException("Username not found: " + username));
}
}
public class UserDetailsImpl implements UserDetails {
private final User user;
public UserDetailsImpl(User user) {
this.user = user;
}
@Override
public Collection
Подробнее здесь: https://stackoverflow.com/questions/789 ... s-as-empty
Spring безопасность загрузки возвращает предоставленные полномочия как пустые ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Почему Spring Security заставляет вас получать полномочия перед проверкой пароля
Anonymous » » в форуме JAVA - 0 Ответы
- 21 Просмотры
-
Последнее сообщение Anonymous
-