Spring Boot 如何禁用特定来源的CSRF

gblwokeq  于 2023-02-08  发布在  Spring
关注(0)|答案(1)|浏览(133)

我需要在Swagger中添加auth,但是我不知道如何将CSRF令牌传递给每个请求。如果我禁用了CSRF令牌保护,那么它可以正常工作,但这不是一个解决方案,所以现在我需要为这个特定的来源禁用CSRF

@Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .and()
                .exceptionHandling().authenticationEntryPoint(authEntryPoint)
                .and()
                .authorizeHttpRequests()
                .antMatchers("/swagger-resources/**","/v2/api-docs","/swagger-     ui/**","/auth/**","/user","/csrf")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(malformedTokenHandler, LogoutFilter.class)
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

我也有这样的SwaggerConfig类:

public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .securityContexts(Arrays.asList(securityContext()))
                .securitySchemes(Arrays.asList(apiKey()))
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    private ApiKey apiKey() {
        return new ApiKey("JWT", "Authorization", "header");
    }
 
    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope
                = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Arrays.asList(new SecurityReference("JWT", authorizationScopes));
    }
 
 private List<Parameter> operationParameters(CsrfTokenRepository csrfTokenRepository) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        CsrfToken csrfToken = csrfTokenRepository.loadToken(request);
        return Arrays.asList(
                new ParameterBuilder()
                        .name("X-CSRF-TOKEN")
                        .modelRef(new ModelRef("string"))
                        .parameterType("header")
                        .defaultValue(csrfToken.getToken())
                        .required(false)
                        .build());
    }
}

我试过:

http.csrf().ignoringAntMatchers("/swagger-resources/**","/v2/api-docs","/swagger-ui/**")

但还是不行。

cld4siwp

cld4siwp1#

试试看:

http.csrf().requireCsrfProtectionMatcher(yourCsrfMatcher)

您将找到类RequestMatcher here的文档:

public class YourCsrfMatcher implements RequestMatcher {
    @override
    public boolean matches(HttpServletRequest request){
         // add your logic here and return false for the specific origin
         return true;
    }  
}

相关问题