0
votes

Swagger OpenAPI 3.0 is working with springdoc-openapi-ui and a custom OpenAPI Bean.

pom.xml

<parent>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-parent</artifactId>
  <version>Hoxton.SR10</version>
</parent>
...
<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-ui</artifactId>
  <version>1.5.5</version>
</dependency>

SwaggerConfig: Custom OpenAPI Bean

The problem with spring-security with the same configuration

We are facing a problem, when using springdoc-openapi-ui, springdoc-openapi-security together with spring-boot-starter-security and keycloak-spring-boot-starter.

pom.xml

<dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-security</artifactId>
      <version>1.5.5</version>
</dependency>
<dependency>
      <groupId>org.keycloak</groupId>
      <artifactId>keycloak-spring-boot-starter</artifactId>
      <version>12.0.2</version>
</dependency>
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
      <version>2.4.2</version>
</dependency>

DummySecurityConfig (profile dev is used currently):

@Profile({"test", "dev"})
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        prePostEnabled = true,
        securedEnabled = true,
        jsr250Enabled = true)
@EnableWebMvc
public class DummySecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

    protected static final String[] ACTUATOR_WHITELIST = {
        "/actuator/**"
    };

    protected static final String[] SWAGGER_WHITELIST = {
        "/v3/api-docs/**",
        "/swagger-ui/**",
        "/swagger-ui.html",
    };

    @Value("${client.cors.allowed-origins:*}")
    private String[] allowedOrigins;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll()
            .anyRequest().authenticated()
            .and()
            .httpBasic(); //or anything else, e.g. .oauth2ResourceServer().jwt()
    }

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


    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
                .antMatchers(SWAGGER_WHITELIST)
                .antMatchers(ACTUATOR_WHITELIST);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins(allowedOrigins);
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        AuthenticationProvider authenticationProvider = new AuthenticationProvider() {
            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + authentication.getPrincipal().toString().toUpperCase());

                UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                        authentication.getPrincipal(), authentication.getCredentials(), Collections.singleton(authority));
                token.setDetails(authentication);
                return token;
            }

            @Override
            public boolean supports(Class<?> aClass) {
                return true;
            }
        };

        return authenticationProvider;
    }
}

SecurityConfig (Not used in the examples but will be used in the future too):

@Profile({"staging", "devstaging"})
@KeycloakConfiguration
@EnableGlobalMethodSecurity(
    prePostEnabled = true,
    securedEnabled = true,
    jsr250Enabled = true)
@EnableWebMvc
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter implements WebMvcConfigurer {

    protected static final String[] ACTUATOR_WHITELIST = {
        "/actuator/**"
    };

    protected static final String[] SWAGGER_WHITELIST = {
        "/v3/api-docs/**",
        "/swagger-ui/**",
        "/swagger-ui.html",
    };

    @Value("${client.cors.allowed-origins:*}")
    private String[] allowedOrigins;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) {
        SimpleAuthorityMapper grantedAuthorityMapper = new SimpleAuthorityMapper();
        grantedAuthorityMapper.setConvertToUpperCase(true);
        grantedAuthorityMapper.setPrefix("ROLE_");

        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(grantedAuthorityMapper);
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Bean
    public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
            .antMatchers(SWAGGER_WHITELIST)
            .antMatchers(ACTUATOR_WHITELIST);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http
            .csrf().disable()
            .cors().and()
            .authorizeRequests().anyRequest().authenticated();
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins(allowedOrigins);
    }
}

application-dev.yml:

server:
  port: 8083
  servlet:
    context-path: /planning
keycloak:
  enabled: false
springdoc:
  show-actuator: true

We already tried to use following links to solve the problem:

Examples of opening the swagger-ui URLs (profile dev):

http://localhost:8083/planning/swagger-ui.html (does not work): http://localhost:8083/planning/swagger-ui.html

Code snippet of application:

2021-03-05 09:27:01,530 [http-nio-8083-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [/planning] threw exception [Could not resolve view with name 'redirect:/swagger-ui/index.html?configUrl=/planning/v3/api-docs/swagger-config' in servlet with name 'dispatcherServlet'] with root cause
javax.servlet.ServletException: Could not resolve view with name 'redirect:/swagger-ui/index.html?configUrl=/planning/v3/api-docs/swagger-config' in servlet with name 'dispatcherServlet'
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1373)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1138)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1077)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)

http://localhost:8083/planning/swagger-ui/index.html?configUrl=/planning/v3/api-docs/swagger-config (works but is complicated): http://localhost:8083/planning/swagger-ui/index.html?configUrl=/planning/v3/api-docs/swagger-config

http://localhost:8083/planning/swagger-ui/index.html (Adding api-docs "/planning/v3/api-docs" manually works too): http://localhost:8083/planning/swagger-ui/index.html

Do you have any ideas what else could be wrong configured or what we should change? We are at the end of our latin.

1

1 Answers

0
votes

As the log says, Could not resolve view with name 'redirect:/swagger-ui/index.html?configUrl=**/planning/v3/api-docs/swagger-config'**. In your web security configuration you only give access to /v3/api-docs/. Try to add /planning/ or modify the path.