2016-06-07 38 views
23

Il mio progetto ha Spring Security. Problema principale: impossibile accedere all'URL swagger a http://localhost:8080/api/v2/api-docs. Dice intestazione di autorizzazione mancante o non valida.Come configurare Spring Security per consentire l'accesso all'URL di Swagger senza autenticazione

Screenshot of the browser window mio pom.xml ha le seguenti voci

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

voci 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); 
    } 
} 

risposta

47

L'aggiunta di questo alla classe WebSecurityConfiguration dovrebbe fare il trucco.

@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

Se si utilizza spavalderia-ui avete bisogno di qualcosa di simile: \t \t \t \t .antMatchers ("/ v2/api-docs", "/ configurazione/ui", "/ spavalderia-risorse" , "/ configuration/security", "/swagger-ui.html", "/ webjars/**", "/ swagger-resources/configuration/ui", "/ swagger-ui.html"). permitAll() –

+2

Nel mio caso questa regola funziona: .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"). permitAll() –

+0

@ nikolai.se rdiuk stai aggiungendo l'endpoint "/ swagge r-ui.html" due volte. Qualche motivo specifico? –

10

Ho aggiornato con/configuration/** e/swagger-resources/** e ha funzionato per me.

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

} 
0

Ho avuto lo stesso problema utilizzando Spring Boot 2.0.0.M7 + Spring Security + Springfox 2.8.0. E ho risolto il problema utilizzando la seguente configurazione di sicurezza che consente l'accesso pubblico alle risorse dell'interfaccia utente di 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

dopo l'aggiunta di questa classe, sono in grado di vedere swagger-ui ma le API non sono accessibili via postman anche con access_token, ottenendo l'accesso vietato errore come sotto, '{ "timestamp": 1.519.798,917075 millions, "status": 403, "errore": "Forbidden", "messaggio": "Accesso negato", "percorso": "/ /negozio" } ' –

+0

@ChandrakantAudhutwar elimina l'istruzione' antMatchers ("/ **"). Authenticated() 'o sostituisce con la propria configurazione di autenticazione. Stai attento, sai cosa stai facendo con sicurezza. – naXa

+0

sì, ha funzionato. Stavo pensando di bypassare solo swagger-ui, ma altre API siccome è sicuro. ora anche le mie API sono bypassate. –

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

Grazie per questo snippet di codice, che potrebbe fornire una guida limitata a breve termine. Una spiegazione appropriata [migliorerebbe notevolmente] (// meta.stackexchange.com/q/114762) il suo valore a lungo termine mostrando * perché * questa è una buona soluzione al problema e lo renderebbe più utile ai futuri lettori con altre domande simili. Per favore [modifica] la tua risposta per aggiungere qualche spiegazione, incluse le ipotesi che hai fatto. –