无法配置Spring Boot安全性 – 始终返回403状态码。

huangapple go评论74阅读模式
英文:

Cannot configure spring boot security - always 403

问题

以下是您提供的内容的翻译部分:

所以我必须配置Spring Security,我相信我漏掉了一些东西,因为它给了我一个403 - 禁止访问的错误。
任何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响应结束。我不明白我漏掉了什么。任何帮助都将是极好的。

英文:

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.

答案1

得分: 3

`new SimpleGrantedAuthority("MY_USER")` 是一种权限而非角色。

你应该使用 `hasAnyAuthority("MY_USER", "MY_ADMIN")` 替代 `hasAnyRole("MY_USER", "MY_ADMIN")`。

编辑:或者你可以使用角色前缀

private String defaultRolePrefix = "ROLE_";

new SimpleGrantedAuthority("ROLE_MY_USER")
英文:

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

huangapple
  • 本文由 发表于 2020年10月21日 21:38:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64464792.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定