java - 无法配置 spring boot 安全 - 总是 403

标签 java spring spring-boot spring-security

所以我必须配置 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/

相关文章:

java - 如何在Spring security 5.0中自定义 token 响应格式

java - Apache Velocity 2.0 脚本编译无法正常工作

spring - 在 Gradle 中排除传递 JAR 依赖项

eclipse - Spring Eclipse 插件更新站点

java - 为什么@EnableWs从spring bean中删除aop代理

spring-boot - Ehcache 3 和 Spring Boot Admin 统计信息

java - 如何解密 Whatsapp 数据库文件?

java - 在 java 中,我想使用 for 循环从整数数组中提取奇数位置的每个数字。我犯了什么错误?

java - Spring AOP 使用方法和参数注解

java - Spring:@Value 在其他类中使用 lombok