So i have to configure spring security and I believe I missing something because it is giving me a 403 - Forbidden. Any spring expert help would be highly appreciated!
I made it a little more simple to focus on the solution, the original code is more complex but the error is still the same.
@EnableWebSecurity
public class WebSecurityConfig {
@Configuration
@Order(1)
public static class JWTSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling()
.authenticationEntryPoint(WebSecurityConfig::handleException)
.and()
.addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/images/**")
.hasAnyRole("MY_USER", "MY_ADMIN")
.anyRequest()
.authenticated();
}
}
}
The filter class is simple and does little:
public class JWTAuthorizationFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
SecurityContextHolder.getContext()
.setAuthentication(new UsernamePasswordAuthenticationToken(
"John Doe",
null,
List.of(new SimpleGrantedAuthority("MY_USER")))
);
} catch (Exception e) {
SecurityContextHolder.clearContext();
}
chain.doFilter(request, response);
}
After I call the REST endpoint:
GET http://localhost:8083/images/parcels/parcel1/data
It always ends up with the spring's default 403 response. I don't see what am I missing. Any help would be great.
new SimpleGrantedAuthority("MY_USER") is an authority not role.
You should use hasAnyAuthority("MY_USER", "MY_ADMIN") instead of hasAnyRole("MY_USER", "MY_ADMIN")
edit: or you can use role prefix
private String defaultRolePrefix = "ROLE_";
--
new SimpleGrantedAuthority("ROLE_MY_USER")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With