Подтвердить что ты не робот

Как настроить Spring Безопасность для доступа к URL-адресу Swagger без проверки подлинности

Мой проект имеет Spring Security. Основная проблема: не удалось получить доступ к свагерскому URL-адресу http://localhost:8080/api/v2/api-docs. Там написано, что заголовок авторизации отсутствует или недействителен.

Снимок экрана из окна браузера В моем pom.xml есть следующие записи

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.4.0</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.4.0</version>
</dependency>

SwaggerConfig:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2).select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .apiInfo(apiInfo());
}

private ApiInfo apiInfo() {
    ApiInfo apiInfo = new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service", "[email protected]", "License of API", "API license URL");
    return apiInfo;
}

AppConfig:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.musigma.esp2" })
@Import(SwaggerConfig.class)
public class AppConfig extends WebMvcConfigurerAdapter {

// ========= Overrides ===========

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LocaleChangeInterceptor());
}

@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/");
}

web.xml записей:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        com.musigma.esp2.configuration.AppConfig
        com.musigma.esp2.configuration.WebSecurityConfiguration
        com.musigma.esp2.configuration.PersistenceConfig
        com.musigma.esp2.configuration.ACLConfig
        com.musigma.esp2.configuration.SwaggerConfig
    </param-value>
</context-param>

WebSecurityConfig:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackages = { "com.musigma.esp2.service", "com.musigma.esp2.security" })
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
        .csrf()
            .disable()
        .exceptionHandling()
            .authenticationEntryPoint(this.unauthorizedHandler)
            .and()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
        .authorizeRequests()
            .antMatchers("/auth/login", "/auth/logout").permitAll()
            .antMatchers("/api/**").authenticated()
            .anyRequest().authenticated();

        // custom JSON based authentication by POST of {"username":"<name>","password":"<password>"} which sets the token header upon authentication
        httpSecurity.addFilterBefore(loginFilter(), UsernamePasswordAuthenticationFilter.class);

        // custom Token based authentication based on the header previously given to the client
        httpSecurity.addFilterBefore(new StatelessTokenAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class);
    }
}
4b9b3361

Ответ 1

Добавление этого в ваш класс WebSecurityConfiguration должно помочь.

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs",
                                   "/configuration/ui",
                                   "/swagger-resources/**",
                                   "/configuration/security",
                                   "/swagger-ui.html",
                                   "/webjars/**");
    }

}

Ответ 2

Я обновил с /configuration/ ** и/swagger-resources/**, и это сработало для меня.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**");

}

Ответ 3

У меня была такая же проблема при использовании Spring Boot 2.0.0.M7 + Spring Security + Springfox 2.8.0. И я решил проблему, используя следующую конфигурацию безопасности, которая разрешает публичный доступ к ресурсам пользовательского интерфейса Swagger.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**"
            // other public endpoints of your API may be appended to this array
    };


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                // ... here goes your custom security configuration
                authorizeRequests().
                antMatchers(AUTH_WHITELIST).permitAll().  // whitelist Swagger UI resources
                // ... here goes your custom security configuration
                antMatchers("/**").authenticated();  // require authentication for any endpoint that not whitelisted
    }

}

Ответ 4

Если ваша версия Springfox выше 2,5 ,, следует добавить WebSecurityConfiguration, как показано ниже:

@Override
public void configure(HttpSecurity http) throws Exception {
    // TODO Auto-generated method stub
    http.authorizeRequests()
        .antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-resources/configuration/security", "/swagger-ui.html", "/webjars/**").permitAll()
        .and()
        .authorizeRequests()
        .anyRequest()
        .authenticated()
        .and()
        .csrf().disable();
}

Ответ 5

Рассматривая все ваши запросы API, расположенные с шаблоном URL /api/.. вы можете сказать Spring, чтобы он защищал только этот шаблон URL, используя приведенную ниже конфигурацию. Это означает, что вы говорите весне, что защищать, а не что игнорировать.

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
    .csrf().disable()
     .authorizeRequests()
      .antMatchers("/api/**").authenticated()
      .anyRequest().permitAll()
      .and()
    .httpBasic().and()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

Ответ 6

Более или менее эта страница имеет ответы, но не все в одном месте. Я имел дело с той же проблемой и провел довольно хорошее время на этом. Теперь у меня есть лучшее понимание, и я хотел бы поделиться этим здесь:

Включение Swagger UI с веб-безопасности Spring:

Если вы включили Spring Websecurity по умолчанию, он заблокирует все запросы к вашему приложению и вернет 401. Однако для загрузки пользовательского интерфейса swagger в браузер swagger-ui.html выполняет несколько вызовов для сбора данных. Лучший способ отладки - это открыть swagger-ui.html в браузере (например, в Google Chrome) и использовать параметры разработчика (клавиша 'F12'). Вы можете увидеть несколько звонков, когда страница загружается и если swagger-ui загружается не полностью, возможно, некоторые из них дают сбой.

вам может потребоваться указать Spring websecurity, чтобы он игнорировал аутентификацию для нескольких шаблонов контуров. Я использую Swagger-UI 2.9.2 и в моем случае ниже шаблоны, которые я должен был игнорировать:

Однако, если вы используете другую версию, вы можете измениться. Возможно, вам придется выяснить свой вариант с разработчиком в вашем браузере, как я уже говорил.

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", 
            "/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
            , "/webjars/**", "/csrf", "/");
}
}

II Включение Swagger UI с перехватчиком

Как правило, вы не хотите перехватывать запросы, сделанные swagger-ui.html. Для исключения нескольких шаблонов чванства ниже приведен код:

В большинстве случаев шаблон для веб-безопасности и перехватчика будет одинаковым.

@Configuration
@EnableWebMvc
public class RetrieveCiamInterceptorConfiguration implements WebMvcConfigurer {

@Autowired
RetrieveInterceptor validationInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {

    registry.addInterceptor(validationInterceptor).addPathPatterns("/**")
    .excludePathPatterns("/v2/api-docs", "/configuration/ui", 
            "/swagger-resources/**", "/configuration/**", "/swagger-ui.html"
            , "/webjars/**", "/csrf", "/");
}

@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/");
}

}

Поскольку вам, возможно, придется включить @EnableWebMvc для добавления перехватчиков, вам также может понадобиться добавить обработчики ресурсов в swagger, как я это делал в приведенном выше фрагменте кода.