Search code examples
spring-bootswagger-ui

Swagger UI stopped working after ContentSecurity policy configuration in sprint-boot version 2.7.3


After we added Swagger security configuration with jwt token, the swagger is not accessible. The error in the console is:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-qzIUUVyNis8jVHXKlYc4HGAEsn0o42pLmW1do84Uptw='), or a nonce ('nonce-...') is required to enable inline execution.

The security configuration code is as below

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

....

    @Override
public void configure(HttpSecurity http) throws Exception {
    http.sessionManagement()
          .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
          .and()
          .exceptionHandling()
          .and()
          .authenticationProvider(provider)
          .addFilterBefore(authenticationFilter(), AnonymousAuthenticationFilter.class)
          .authorizeRequests()
          .requestMatchers(PROTECTED_URLS)
          .authenticated()
          .and()
          .csrf().disable().cors()
          .and()
          .formLogin().disable()
          .httpBasic().disable()
          .logout().disable();
    http.headers().frameOptions().sameOrigin();
    http.headers().contentSecurityPolicy("script-src 'self'");
}

The problem started after the last line in this configuration:

http.headers().contentSecurityPolicy("script-src 'self'");

If we remove this, the swagger works. We also tried wirht 'none' instead of 'self'. are we missing any annotation? please help.

We also tried with Controller Class Annotations, as shown below. this is also not working.

@SecurityScheme(name = "bearerToken", type = SecuritySchemeType.HTTP, scheme = "bearer", bearerFormat = "JWT", in = SecuritySchemeIn.HEADER )

and Method Annotations.

@SecurityRequirement(name = "bearerToken")

Solution

  • We could solve this issue by upgrading swaggr UI dependency from 1.5 to 1.8