繁体   English   中英

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

[英]Cannot configure spring boot security - always 403

所以我必须配置 spring 安全性,我相信我错过了一些东西,因为它给了我一个 403 - Forbidden。 任何弹簧专家的帮助将不胜感激!

我把重点放在解决方案上更简单一点,原始代码更复杂但错误仍然相同。

@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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM