Как настроить Spring Security, чтобы разрешить доступ к URL Swagger без аутентификации

В моем проекте есть Spring Security. Основная проблема: невозможно получить доступ к URL-адресу swagger по адресу 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);
    }
}

person shubhendu_shekhar    schedule 07.06.2016    source источник


Ответы (11)


Добавление этого в ваш класс 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/**");
    }

}
person Stijn Maller    schedule 07.06.2016
comment
Если вы используете swagger-ui, вам понадобится что-то вроде этого: .antMatchers (/ v2 / api-docs, / configuration / ui, / swagger-resources, / configuration / security, /swagger-ui.html, / webjars / **, /swagger-resources/configuration/ui,/swagger-ui.html) .permitAll () - person Daniel Martín; 23.01.2017
comment
В моем случае это правило работает: .antMatchers (/ v2 / api-docs, / configuration / ui, / swagger-resources, / configuration / security, /swagger-ui.html, / webjars / **, / swagger-resources / конфигурация / пользовательский интерфейс, / swagge‌ r-ui.html, / swagger-ресурсы / конфигурация / безопасность) .permitAll () - person nikolai.serdiuk; 02.03.2017
comment
Требуется больше правил: .antMatchers (/, / csrf, / v2 / api-docs, / swagger-resources / configuration / ui, / configuration / ui, / swagger-resources, / swagger-resources / configuration / security, / configuration / безопасность, /swagger-ui.html, / webjars / **). allowAll () - person Mate Šimović; 10.07.2018
comment
Спасибо за ответ! Есть ли угроза безопасности при доступе к веб-файлам / **? - person ssimm; 16.11.2018
comment
очень полезный ответ - person Praveenkumar Beedanal; 01.09.2020
comment
Мне пришлось добавить .., "/swagger-ui/**"... в этот список - person FourtyTwo; 17.01.2021
comment
@FourtyTwo меня тоже, потому что Springfox 3.0.0 изменил путь. - person Fabio Cardoso; 24.01.2021

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

Ответ обновлен в январе 2021 года: поддержка Springfox 3

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

    private static final String[] AUTH_WHITELIST = {
            // -- Swagger UI v2
            "/v2/api-docs",
            "/swagger-resources",
            "/swagger-resources/**",
            "/configuration/ui",
            "/configuration/security",
            "/swagger-ui.html",
            "/webjars/**",
            // -- Swagger UI v3 (OpenAPI)
            "/v3/api-docs/**",
            "/swagger-ui/**"
            // 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's not whitelisted
    }

}
person naXa    schedule 25.02.2018
comment
после добавления этого класса я могу видеть swagger-ui, но API-интерфейсы не доступны через почтальон даже с access_token, получая доступ к запрещенной ошибке, как показано ниже, { "timestamp": 1519798917075, "status": 403, "error": "Forbidden", "message": "Access Denied", "path": "/<some path>/shop" } - person Chandrakant Audhutwar; 28.02.2018
comment
@ChandrakantAudhutwar удалите оператор antMatchers("/**").authenticated() или замените его собственной конфигурацией аутентификации. Будьте осторожны, вам лучше знать, что вы делаете с безопасностью. - person naXa; 28.02.2018
comment
да, сработало. Я думал только об обходе swagger-ui, но других API, поскольку он защищен. теперь мои API тоже обойдены. - person Chandrakant Audhutwar; 28.02.2018
comment
@ChandrakantAudhutwar, вам не нужно копировать и вставлять весь класс SecurityConfiguration в свой проект. У вас должен быть собственный SecurityConfiguration, где вы разрешаете запросы к ресурсам пользовательского интерфейса Swagger и обеспечиваете безопасность ваших API. - person naXa; 28.02.2018
comment
У меня есть AuthorizationServerConfigurerAdapter реализованный класс, который выполняет аутентификацию API. - person Chandrakant Audhutwar; 28.02.2018
comment
@ChandrakantAudhutwar хочет объяснить, как вы решили свою проблему? Я также могу получить доступ к своей странице swagger, но когда я нажимаю "Попробовать", тело ответа - это страница входа, поэтому она перенаправляется - person GSUgambit; 07.03.2018
comment
@ChandrakantAudhutwar, как будто мне нужно найти способ придать чванству роль безопасности, чтобы он не был анонимным, я вижу это в своих журналах: ossaccess.vote.AffirmativeBased: Voter: org.springframework.security.web.access.expression.WebExpressionVoter @ 1afeff6, возвращено: -1 osswaExceptionTranslationFilter: доступ запрещен (пользователь анонимен); перенаправление к точке входа аутентификации - person GSUgambit; 07.03.2018
comment
Я знаю, что это старый ответ, но если вы добавите / swagger-ui / ** в список, он будет идеальным. URL Springfox 3.0.0 таков. - person Fabio Cardoso; 24.01.2021
comment
@FabioCardoso, спасибо за предложение. Я обновил ответ. - person naXa; 25.01.2021

Я обновился с помощью / 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/**");

}
person Akshata Suvarna    schedule 09.08.2017
comment
Идеально! Решил вопрос. - person Madhu; 26.07.2019

Для тех, кто использует более новую версию swagger 3 org.springdoc:springdoc-openapi-ui

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v3/api-docs/**", "/swagger-ui.html", "/swagger-ui/**");
    }
}
person Dennis Gloss    schedule 10.04.2020
comment
Примечание. Если это мешает вам получить ошибку «Требуется аутентификация», но показывает вам пустую страницу, мне также пришлось добавить / swagger-resources / ** и / swagger-resources в этот список, и он исправил это для меня. - person Vinícius M; 24.06.2020

если ваша версия 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();
}
person duliu1990    schedule 13.05.2018
comment
duliu1990 прав, так как springfox 2.5+ все ресурсы springfox (включая swagger) переместились в /swagger-resources. /v2/api-docs - конечная точка api swagger по умолчанию (не имеет отношения к пользовательскому интерфейсу), которую можно переопределить с помощью переменной конфигурации springfox.documentation.swagger.v2.path springfox - person Mahieddine M. Ichir; 23.08.2018

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

I Включение пользовательского интерфейса Swagger с помощью веб-безопасности Spring:

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

вам может потребоваться указать Spring websecurity игнорировать аутентификацию для нескольких шаблонов пути swagger. Я использую 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 с перехватчиком

Как правило, вы можете не захотеть перехватывать запросы, сделанные 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, аналогично тому, что я сделал в приведенном выше фрагменте кода.

person chanderdevx    schedule 28.01.2019
comment
Почему вы добавляете /csrf в исключение? - person Vishal; 14.07.2019

Ограничение только ресурсами, связанными с Swagger:

.antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html", "/webjars/springfox-swagger-ui/**");
person m52509791    schedule 02.11.2019

Вот полное решение для Swagger с Spring Security. Вероятно, мы хотим включить Swagger только в нашей среде разработки и контроля качества и отключить его в производственной среде. Итак, я использую свойство (prop.swagger.enabled) в качестве флага для обхода аутентификации безопасности Spring для swagger-ui только в среде development / qa.

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

@Value("${prop.swagger.enabled:false}")
private boolean enableSwagger;

@Bean
public Docket SwaggerConfig() {
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(enableSwagger)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.your.controller"))
            .paths(PathSelectors.any())
            .build();
}

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

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (enableSwagger) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
  }
}
person Abdul Rahman    schedule 28.11.2019

Некоторая конфигурация безопасности, и вы готовы с чванством, открытым для всех

Для Swagger V2

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {


    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs", 
            "/swagger-resources/**", 
            "/configuration/ui",
            "/configuration/security", 
            "/swagger-ui.html",
            "/webjars/**"
    };

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

        // ... here goes your custom security configuration
        http.authorizeRequests().
        antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
        antMatchers("/**").authenticated(); // others need auth
    }

}

Для Swagger V3

@Configuration
@EnableWebSecurity
public class CabSecurityConfig extends WebSecurityConfigurerAdapter {


    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/v2/api-docs",
            "/v3/api-docs",  
            "/swagger-resources/**", 
            "/swagger-ui/**",
             };

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

        // ... here goes your custom security configuration
        http.authorizeRequests().
        antMatchers(AUTH_WHITELIST).permitAll(). // whitelist URL permitted
        antMatchers("/**").authenticated(); // others need auth
    }

}
person Rupesh Kumar    schedule 15.12.2020

Я использую Spring Boot 5. У меня есть этот контроллер, который должен вызывать неаутентифицированный пользователь.

  //Builds a form to send to devices   
@RequestMapping(value = "/{id}/ViewFormit", method = RequestMethod.GET)
@ResponseBody
String doFormIT(@PathVariable String id) {
    try
    {
        //Get a list of forms applicable to the current user
        FormService parent = new FormService();

Вот что я сделал в настройке.

  @Override
   protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers(
                    "/registration**",
                    "/{^[\\\\d]$}/ViewFormit",

Надеюсь это поможет....

person smac2020    schedule 11.05.2020

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

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
    .csrf().disable()
     .authorizeRequests()
      .antMatchers("/api/**").authenticated()
      .anyRequest().permitAll()
      .and()
    .httpBasic().and()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
person Siddu    schedule 07.03.2018
comment
Спасибо за этот фрагмент кода, который может предоставить некоторую краткосрочную помощь. Правильное объяснение значительно улучшило бы его долгосрочную ценность, показав почему это хорошее решение проблема, и сделает ее более полезной для будущих читателей с другими похожими вопросами. Пожалуйста, отредактируйте свой ответ, чтобы добавить пояснения, включая сделанные вами предположения. - person Toby Speight; 07.03.2018