【问题标题】:Spring security permitall return 401Spring安全许可全部返回401
【发布时间】:2021-11-18 22:41:40
【问题描述】:

Spring 安全配置

 @Override
    protected void configure(HttpSecurity http) throws Exception {

    http.cors().and()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()
            .antMatchers("/admin").hasRole("ADMIN")
            .antMatchers("/api/auth/**").permitAll()
            .antMatchers("/api/test/**").permitAll()
            .antMatchers("/").permitAll()
            .antMatchers("/favicon.ico").permitAll()
            .antMatchers("/static/**").permitAll()
            .antMatchers("/manifest.json").permitAll()
            .antMatchers("/logo192.png").permitAll()
            .anyRequest().authenticated();

    http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}

我也试过了,但没有产生任何结果

.antMatchers(HttpMethod.POST, "/api/auth/**").permitAll()

/api/auth/注册返回

error: "Unauthorized"
message: "Full authentication is required to access this resource"
path: "/error"
status: 401

Request URL: https://mysuite.ru/api/auth/signup

我该如何解决这个问题?

更新

@Configuration
public class MvcSecurityConfig implements WebMvcConfigurer {
@Value("${path.frontend}")
private String frontendPath;
@Value("${frontendStaticResourcesPathPatterns}")
private String[] frontendStaticResourcesPathPatterns;
private static final String BASE_API_PATH = "/";

public void addResourceHandlers(ResourceHandlerRegistry registry){
    String pathToFrontend = "file:" + this.frontendPath;
    String pathToIndexHTML = pathToFrontend + "/index.html";

    registry
            .addResourceHandler(frontendStaticResourcesPathPatterns)
            .setCachePeriod(0)
            .addResourceLocations(pathToFrontend);

    registry.addResourceHandler("/", "/**")
            .setCachePeriod(0)
            .addResourceLocations(pathToIndexHTML)
            .resourceChain(true)
            .addResolver(new PathResourceResolver() {
                @Override
                protected Resource getResource(String resourcePath, Resource location) throws IOException {
                    if (resourcePath.startsWith(BASE_API_PATH) || resourcePath.startsWith(BASE_API_PATH.substring(1))) {
                        return null;
                    }
                    return location.exists() && location.isReadable() ? location : null;
                }
            });

}
}

这是我的 Spring MVC 配置。 这会导致问题吗? 我也尝试沿着路径一步一步地做 permitAll 但它不起作用(api/,api/auth,api/autn/**)

【问题讨论】:

    标签: spring spring-boot spring-mvc spring-security


    【解决方案1】:

    在 Ant 匹配器中,** 匹配路径中的零个或多个目录。给定您的请求 URL,您只需要匹配零个或多个字符。话虽如此,请尝试将您的 Ant 匹配器替换为以下内容:

    .antMatchers(HttpMethod.POST, "/api/auth/*").permitAll()
    

    【讨论】:

    • 结果是一样的
    • 如果您删除所有其他 Ant 匹配器并仅使用 antMatchers("/api/**").permitAll() 会发生什么?
    • 我删除了所有内容,只留下了这个,结果没有改变
    【解决方案2】:

    通过您的过滤器,因为任何 API 请求都通过过滤器。您的 API 无法通过过滤器,因此您得到 401 响应。

    尝试将此添加到您的 Spring 安全配置中:

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api/auth/**");
    }
    

    或将其添加到 OncePerRequestFilter:

        @Override
        protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
            return new AntPathMatcher().match("/api/auth/**", request.getServletPath());
        }
    

    【讨论】:

      【解决方案3】:

      默认情况下,Spring Security 启用了 CSRF 保护,因此当您执行不安全的请求(POST、PUT、DELETE)时,您必须提供 CSRF 令牌

      在您的配置方法中,您可以禁用它以检查它是否可以工作。

      http.csrf().disable()
      

      我建议您禁用 CSRF 保护可能对您的应用有害,您应该确定是否需要使用它。

      另外,如果您使用的是 Spring Security 的 5.4 或更高版本,您可以启用跟踪日志来帮助您调试它。

      logging.level.org.springframework.security=TRACE

      您可以在reference docs获取更多详细信息。

      【讨论】:

        猜你喜欢
        • 2020-10-03
        • 2016-10-16
        • 2017-01-26
        • 1970-01-01
        • 2019-02-01
        • 2021-06-06
        • 1970-01-01
        • 2020-11-20
        • 2013-09-10
        相关资源
        最近更新 更多