2016-06-07 8 views
23

У моего проекта есть Spring Security. Основная проблема: не удалось получить доступ к URL-адресу разворота по адресу http://localhost:8080/api/v2/api-docs. В нем указано Недопустимый или недействительный заголовок авторизации.Как настроить Spring Security для доступа к URL-адресу Swagger без аутентификации

Screenshot of the browser window Мой 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); 
    } 
} 

ответ

47

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

} 
+5

Если вы используете чванство-UI вам нужно что-то вроде этого: \t \t \t \t .antMatchers ("/ v2/API-документы", "/ конфигурация/щ", "/ чванство-ресурсы" , "/ configuration/security", "/swagger-ui.html", "/ webjars/**", "/ swagger-resources/configuration/ui", "/ swagger-ui.html"). allowAll() –

+2

В моем случае это правило работает: .antMatchers («/ v2/api-docs», «/ configuration/ui», «/ swagger-resources», «/ configuration/security», «/swagger-ui.html», "/ webjars/**", "/ swagger-resources/configuration/ui", "/ swagge r-ui.html", "/ swagger-resources/configuration/security"). allowAll() –

+0

@ nikolai.se rdiuk вы добавляете «/ swagge r-ui.html» оконечную точку дважды. Любая конкретная причина? –

10

Я обновил/конфигурировал/** и/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/**"); 

} 
0

У меня была такая же проблема с использованием 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's not whitelisted 
    } 

} 
+0

после добавления этого класса, я могу видеть swagger-ui, но API-интерфейсы не доступны через почтальон, даже с access_token, доступ к запрещенной ошибке как показано ниже, '{ "метка": 1519798917075, "статус": 403, "ошибка": "Forbidden", "сообщение": "Отказано в доступе", "путь": "/ /магазин" } ' –

+0

@ChandrakantAudhutwar удаляет' antMatchers ("/ **"). Authenticated() 'statement или replace с вашей собственной конфигурацией проверки подлинности. Будьте осторожны, вам лучше знать, что вы делаете с безопасностью. – naXa

+0

Да, это сработало. Я думал о том, чтобы обойти swagger-ui, но другие API-интерфейсы, поскольку они защищены. теперь мои API также обойдутся. –

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

Благодарим вас за этот фрагмент кода, который может предоставить некоторую ограниченную краткосрочную помощь. Правильное объяснение [значительно улучшило бы] (// meta.stackexchange.com/q/114762) его долгосрочную ценность, показав * почему * это хорошее решение проблемы и сделало бы его более полезным для будущих читателей с другие, подобные вопросы. Пожалуйста, отредактируйте свой ответ, чтобы добавить какое-то объяснение, включая сделанные вами предположения. –