Spring безопасность загрузки возвращает предоставленные полномочия как пустыеJAVA

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

Сообщение Anonymous »

Я использую 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
Реклама
Ответить Пред. темаСлед. тема

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

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

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

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

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

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