所以我必须配置 spring security,我相信我错过了一些东西,因为它给了我一个 403 - Forbidden。 非常感谢任何 spring 专家的帮助!
我把重点放在了解决方案上,让它更简单了一点,原来的代码更复杂了,但错误还是一样。
@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();
}
}
}
过滤器类很简单,做的事情很少:
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);
}
调用 REST 端点后:
GET http://localhost:8083/images/parcels/parcel1/data
它总是以 spring 的默认 403 响应结束。我不明白我错过了什么。任何帮助都会很棒。
最佳答案
new SimpleGrantedAuthority("MY_USER")
是权限而非角色。
您应该使用 hasAnyAuthority("MY_USER", "MY_ADMIN")
而不是 hasAnyRole("MY_USER", "MY_ADMIN")
编辑:或者你可以使用角色前缀
private String defaultRolePrefix = "ROLE_";
--
new SimpleGrantedAuthority("ROLE_MY_USER")
关于java - 无法配置 spring boot 安全 - 总是 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64464792/