I'm using Oauth2 resource server JWT for authentication. I'm trying to add authentication for two routes , route "/student/" to give acess to role ROLE_USER and route "/students/" to role ROLE_ADMIN.
Security config
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
return httpSecurity
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(a ->
{
a.requestMatchers("/student/").hasAnyRole("ROLE_USER");
a.requestMatchers("/student/**").hasAnyRole("ROLE_USER");
a.requestMatchers("/students/").hasAnyRole("ROLE_ADMIN");
a.requestMatchers("/students/**").hasAnyRole("ROLE_ADMIN");
a.requestMatchers("/").permitAll();
a.requestMatchers("/token/").permitAll();
a.requestMatchers("/token/**").permitAll();
a.anyRequest().authenticated();
})
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.userDetailsService(userDetailsService)
.headers(headers -> headers.frameOptions().sameOrigin())
.httpBasic(Customizer.withDefaults())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.build();
}
I tried to change hasRole()
to hasAnyRole()
, hasAuthority()
, treid @PreAuthorize()
on controller and checked with using roles without "ROLE_
" prefix but nothing has worked.
UserDetailsService
public class jpaUserDetailsService implements UserDetailsService {
UserRepository userRepository;
public jpaUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepository.findUserByUsername(username)
.map(SecurityUser::new)
.orElseThrow(() -> new UsernameNotFoundException("Username not found " + username));
}
}
UserDetails
public class SecurityUser implements UserDetails {
public Collection<? extends GrantedAuthority> getAuthorities() {
return user.getRoles().stream()
.map(Role::getRole)
.map(UserRoles::toString)
.map(SimpleGrantedAuthority::new).toList();
}
}
I am using an enum for all my Roles
public enum UserRoles {
ROLE_ADMIN,
ROLE_USER
}
Service to generate jwt Token
public class TokenService {
private final JwtEncoder jwtEncoder;
public TokenService(JwtEncoder jwtEncoder) {
this.jwtEncoder = jwtEncoder;
}
public String generateToken(Authentication authentication){
Instant now = Instant.now();
String scope = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(" "));
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(now.plus(1 , ChronoUnit.HOURS))
.subject(authentication.getName())
.claim("scope" , scope)
.build();
return this.jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
}
User Entity
public class User {
@Id
@GeneratedValue
private long userId;
@Column(unique = true , nullable = false)
private String username;
@Column(nullable = false)
private String password;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
joinColumns = @JoinColumn(name = "userId"),
inverseJoinColumns = @JoinColumn(name = "roleId")
)
@ToString.Exclude
private List<Role> roles;
}
Role Entity
public class Role {
@Id
@GeneratedValue
private Long roleId;
@Column(unique = true , nullable = false)
@Enumerated(EnumType.STRING)
private UserRoles role;
}
finally my Contoroller
@GetMapping("/student/") // route i want to allow with role user;
public Student getStudent(Principal principal){
}
@GetMapping("/students/") // route i want to allow only role admin
public List<Student> getStudents(Principal principal){
}
}