401 unauthorized page for swagger-ui

Viewed 938

I have a problem with springfox in particular with swagger-ui. I have added this dependencies of springfox in my pom.xml:

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

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

but when I reach swagger-ui with the url localhost:8889/app/swagger-ui.html it come back to me error 401 (my context path is '/app' and my web server start on port 8889(http)). I have also tried with the following url:

  • localhost:8889/app/swagger-ui
  • localhost:8889/swagger-ui.html
  • localhost:8889/swagger-ui

but the result is always the same. I have tried to reach the localhost:8889/app/v2/api-docs and this works fine (I see the json value not in human format), so swagger is working

I have configured a class of configuration for swagger in this way:

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer{

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


private ApiInfo apiInfo() {
    ApiInfoBuilder apiInfoBuilder = new ApiInfoBuilder();
    apiInfoBuilder.title("REST API");
    apiInfoBuilder.description("REST API GENERATION");
    apiInfoBuilder.version("1.0.0");
    apiInfoBuilder.license("GNU GENERAL PUBLIC LICENSE, Version 3");
    apiInfoBuilder.licenseUrl("https://www.gnu.org/licenses/gpl-3.0.en.html");
    return apiInfoBuilder.build();
}

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

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addRedirectViewController("/api/v2/api-docs", "/v2/api-docs");
    registry.addRedirectViewController("/api/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
    registry.addRedirectViewController("/api/swagger-resources/configuration/security", "/swagger-resources/configuration/security");
    registry.addRedirectViewController("/api/swagger-resources", "/swagger-resources");
}

}

I have configured also a spring security class and I have modified the configure method to ignore this request pattern:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@PropertySource(encoding = "UTF-8", value = {"classpath:commons-web- 
config.properties"}, ignoreResourceNotFound = false)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

@Autowired
private TokenAuthenticationProvider authenticationProvider;

private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
            new AntPathRequestMatcher("/public/login/login-user")
        );

private static final RequestMatcher PROTECTED_URLS = new NegatedRequestMatcher(PUBLIC_URLS);


@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider);
}

@Override
public void configure(WebSecurity web) {
    web
    .ignoring()
    .requestMatchers(PUBLIC_URLS);
    web
    .ignoring()
    .antMatchers("/v2/api-docs/**", "/swagger-ui/**", "/swagger-ui.html", "/public/**", "/websocket/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception{
    http
        .sessionManagement().sessionCreationPolicy(STATELESS)
        .and()
        .csrf()
        .disable()
        .authorizeRequests()
        .antMatchers("/protected/my-controller")
        .hasAnyRole("SUPER-ADMIN","ADMIN","USER")
        .and()
        .exceptionHandling()
        .defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
        .and()
        .authenticationProvider(authenticationProvider)
        .addFilterBefore(restAuthenticationFilter(), AnonymousAuthenticationFilter.class)
        .authorizeRequests()
        .anyRequest()
        .authenticated()
        .and()
        .formLogin().disable()
        .httpBasic().disable()
        .logout().disable();
}

   @Bean
   public AuthenticationEntryPoint forbiddenEntryPoint() {
       return new HttpStatusEntryPoint(FORBIDDEN);
   }

   @Bean
   public TokenAuthenticationFilter restAuthenticationFilter() throws Exception {
       TokenAuthenticationFilter filter = new TokenAuthenticationFilter(PROTECTED_URLS);
       filter.setAuthenticationManager(authenticationManager());
       filter.setAuthenticationSuccessHandler(successHandler());
       return filter;
   }
   
   @Bean
   public SimpleUrlAuthenticationSuccessHandler successHandler() {
       SimpleUrlAuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler();
       successHandler.setRedirectStrategy(new NoRedirectStrategy());
       return successHandler;
   }
   
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

   @Bean
   public FilterRegistrationBean<TokenAuthenticationFilter> disableAutoRegistration(TokenAuthenticationFilter filter) {
       FilterRegistrationBean<TokenAuthenticationFilter> registration = new FilterRegistrationBean<TokenAuthenticationFilter>(filter);
       registration.setEnabled(false);
       return registration;
   }

}

I can't find the error. I believe it is in the spring security config class. Can anyone help me?

P.S. My spring boot version is 2.4.5

0 Answers
Related