Hi i was implementing jwt role based auth in spring latest version. Everything is working fine but role based is always giving 403 to me here are some of my files
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class MySecurityConfig {
@Autowired
private JwtAuthFilter jwtAuthFilter;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.csrf().disable()
.authorizeHttpRequests().requestMatchers("/users/auth").permitAll()
.and()
.authorizeHttpRequests().anyRequest().authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider())
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class).build();
}
@Bean
public UserDetailsService userDetailsService(){
return new UserInfoUserService();
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider authenticationProvider=new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService());
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception{
return config.getAuthenticationManager();
}
}
UserInfo
public class UserInfoUserDetails implements UserDetails {
private long uid;
private String password;
private String username;
private List<GrantedAuthority> authorities;
public UserInfoUserDetails(Users userInfo) {
System.out.println(userInfo.getRole()+" "+userInfo.getPassword()+" "+userInfo.getUsername());
uid=userInfo.getId();
password=userInfo.getPassword();
username=userInfo.getUsername();
authorities= Arrays.stream(userInfo.getRole().split(",")).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
AuthFilter
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String authHeader=request.getHeader("Authorization");
String token=null;
String username=null;
if(authHeader!=null && authHeader.startsWith("Bearer ")){
token=authHeader.substring(7);
username= jwtService.extractUsername(token);
}
if(username!=null && SecurityContextHolder.getContext().getAuthentication()==null){
UserDetails userDetails=userInfoUserService.loadUserByUsername(username);
System.out.println("User: " + userDetails.getAuthorities());
if(jwtService.validateToken(token,userDetails)){
UsernamePasswordAuthenticationToken authtoken=new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
authtoken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authtoken);
}
}
filterChain.doFilter(request,response);
}
Please Help
I have some endpoints i am using @PreAuthorize("hasAuthority('ROLE_USER')") for role based auth. In my db I have role set as ROLE_USER but still
@GetMapping(path="/user")
@PreAuthorize("hasAuthority('ROLE_USER')")
public String user(){
return "User role";
}
is returning 403
Comment From: scottfrederick
Thanks for getting in touch and for sharing your code. Unfortunately even with the code you've shared there are details of your configuration that could be missing. If you would like us to spend some time investigating, please provide a complete minimal sample that reproduces the problem. The sample should have instructions for running it and observing the failing behavior, without requiring a database. You can share it with us by pushing it to a separate repository on GitHub or by zipping it and attaching it to this issue.
Comment From: spring-projects-issues
If you would like us to look at this issue, please provide the requested information. If the information is not provided within the next 7 days this issue will be closed.
Comment From: spring-projects-issues
Closing due to lack of requested feedback. If you would like us to look at this issue, please provide the requested information and we will re-open the issue.