简体   繁体   English

“ addCorsMapping”阻止Swagger UI

[英]“addCorsMapping” blocking Swagger UI

I'm working on a Spring application and I have some troubles with Swagger and Spring Security. 我正在使用Spring应用程序,但是Swagger和Spring Security遇到了一些麻烦。 I had to add a specific configuration to allow almost every access (CORS) and it worked well so far, but somehow it is blocking Swagger.... 我必须添加一个特定的配置以允许几乎所有访问(CORS),并且到目前为止效果良好,但是不知何故,它阻止了Swagger ....

This is my SwaggerConfiguration.java 这是我的SwaggerConfiguration.java

@Configuration
@EnableSwagger2
@SwaggerDefinition(
        info = @Info(
                description = "Web Service",
                version = "V0.0.1",
                title = "Web Service",
                contact = @Contact(
                        name = "Me",
                        email = "dev@me.com",
                        url = "https://www.me.com/"
                )
        ),
        consumes = {"application/json"},
        produces = {"application/json"},
        schemes = {SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS}
)
public class SwaggerConfiguration {

    /** List of Swagger endpoints (used by {@code WebSecurityConfig}) */
    static final String[] SWAGGER_ENDPOINTS = {
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**"
    };

    @Bean
    public Docket swaggerSpringMvcPlugin() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("admin-api")
                .select()
                .paths(paths()) // and by paths
                .build();
    }

    private Predicate<String> paths() {
        return or(
                regex("/admin.*"),
                regex("/issuer.*"),
                regex("/validator.*"),
                regex("/data.*"));

    }
}

And this is my WebSecurityConfig.java : 这是我的WebSecurityConfig.java:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtTokenDecoder jwtTokenDecoder;


    @Bean
    // Mandatory to be able to have % in URL
    // FIXME Set it only for dev environment
    public HttpFirewall allowUrlEncodedPercentHttpFirewall() {
        StrictHttpFirewall firewall = new StrictHttpFirewall();
        firewall.setAllowUrlEncodedPercent(true);
        firewall.setAllowUrlEncodedSlash(true);

        return firewall;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .httpBasic().disable()
                .formLogin().disable()
                .logout().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Install the JWT authentication filter
        http.addFilterBefore(new JwtAuthenticationFilter(jwtTokenDecoder), BasicAuthenticationFilter.class);

        // Authorize only authenticated requests
        http.authorizeRequests()
                .anyRequest().authenticated();

       http.cors();
    }

    @Override
    public void configure(WebSecurity web) {
        // Allow access to /admin/login without authentication
        web.ignoring().mvcMatchers("/admin/login", "/admin/validate", "/campaigns", "/data/**", "/issuer/**", "/validator/**");
        web.ignoring().antMatchers(SwaggerConfiguration.SWAGGER_ENDPOINTS);
        web.httpFirewall(allowUrlEncodedPercentHttpFirewall());
    }
}

Finally, I have a WebConfig.java used to set CORS authorizations. 最后,我有一个WebConfig.java用于设置CORS授权。 Here it is : 这里是 :

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE");
    }
}

Very simple. 很简单。 It should authorize almost any access. 它应该授权几乎所有访问。 When I remove it, Swagger is available from URL localhost:8080/swagger-ui.html (but not my webservices...) When I put it back, it is blocked, with a 403 error (forbidden) 当我删除它时,可以从URL localhost:8080 / swagger-ui.html(但不是我的webservices ...)中获得Swagger。当我放回它时,它被阻止,并显示403错误(禁止)

Any idea of what I am missing ? 有什么想法我想念的吗?

So the solution was to add some configuration in WebConfig 所以解决方案是在WebConfig添加一些配置

I have added this implementation 我添加了此实现

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

    registry
            .addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

    registry
            .addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

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

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