Я использую 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
Программисты JAVA общаются здесь
1726641999
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
Подробнее здесь: [url]https://stackoverflow.com/questions/78996874/spring-boot-security-returning-granted-authorities-as-empty[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия