I am developing a web app with spring security and have an issue with roles
requests are always forbidden even if user have apropriate role
here area code:
public class SecurityConfig {
@Value("${jwt.public.key}")
RSAPublicKey publicKey;
@Value("${jwt.private.key}")
RSAPrivateKey privateKey;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity.csrf(AbstractHttpConfigurer::disable)
.cors(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/api/**")
.permitAll()
.requestMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**")
.permitAll()
.anyRequest()
.authenticated())
.oauth2ResourceServer((oauth2) -> oauth2
.jwt(Customizer.withDefaults()))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(exceptions -> exceptions
.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
.accessDeniedHandler(new BearerTokenAccessDeniedHandler())
)
.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
JwtDecoder jwtDecoder() {
return NimbusJwtDecoder.withPublicKey(this.publicKey).build();
}
@Bean
JwtEncoder jwtEncoder() {
JWK jwk = new RSAKey.Builder(this.publicKey).privateKey(this.privateKey).build();
JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
return new NimbusJwtEncoder(jwks);
}
}
method from controller
@PreAuthorize("hasRole('USER')")
@PostMapping
public ResponseEntity<SubthreadDto> createSubthread(@RequestBody SubthreadDto subthreadDto) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(subthreadService.save(subthreadDto));
}
custom user detail service
public class CustomUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) {
UserEntity user = userRepository.findByUsername(username)
.orElseThrow(() -> new ThreadboardException("No user found with username - " + username));
System.out.println(getAuthorities(user.getRole()));
return User.withUsername(username)
.password(user.getPassword())
.roles("USER")
.build();
}
private Collection<? extends GrantedAuthority> getAuthorities(String role) {
return singletonList(new SimpleGrantedAuthority(role));
}
}
tried everything but still don’t have clue how to fix it
really exhausted with this spent 2 days fixing it
New contributor
asphx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.