title: Secure Springfox Swagger2 UI
body: <p>I am using springfox swagger2 and it is working right.<br>
  It was just a basic setup/configuration as I am really new with swagger.</p>
  
  <p>But it is accessible to all who have the url.</p>
  
  <p>I would like it not to be accessible to everyone and to have a login screen (Basic authentication or google authentication) would really be great.</p>
  
  <p>I have been looking over the internet but it seems I cannot find something specific to springfox-swagger2. I can find some but it seems it is for .Net (C# based samples).</p>
  
  <p><strong>Update</strong></p>
  
  <p>I can access <code>swagger-ui.html</code> if I set this <code>.antMatchers("/swagger-ui.html**").permitAll()</code> in <code>SecurityConfig</code> class.</p>
  
  <p>But if I change it to <code>.authenticated()</code>, it won't and I am getting the 401 error I set:</p>
  
  <pre><code>{"timestamp":"2018-09-03T06:06:37.882Z","errorCode":401,"errorMessagesList":[{"message":"Unauthorized access"}]}
  </code></pre>
  
  <p>It seems it hits my authentication entry point. If I can only make <code>swagger-ui.html</code> (or swagger as a whole) be accessible only to all authenticated users (for now, and will be based on roles later on).</p>
  
  <p>I am not sure if I need to add some security configuration on <code>SwaggerConfig.java</code> since I only need to make <code>swagger-ui.html</code> available to authenticated users (or specific roles/authority).</p>
  
  <p><strong>Dependency (pom.xml):</strong></p>
  
  <pre><code>&lt;dependency&gt;
    &lt;groupId&gt;io.springfox&lt;/groupId&gt;
    &lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt;
    &lt;version&gt;2.8.0&lt;/version&gt;
  &lt;/dependency&gt;
  </code></pre>
  
  <p><strong>Security Configuration class</strong></p>
  
  <pre><code>@EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      ...
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          JWTAuthenticationFilter authenticationFilter =
                  new JWTAuthenticationFilter(authenticationManager(), appContext);
          authenticationFilter.setFilterProcessesUrl("/auth/form");
  
          JWTAuthorizationFilter authorizationFilter =
                  new JWTAuthorizationFilter(authenticationManager(), appContext);
  
          http
              .cors().and().csrf().disable() // no need CSRF since JWT based authentication
              .authorizeRequests()
  
              ...
  
              .antMatchers("/swagger-ui.html**").authenticated()
  
              ...
  
              .anyRequest().authenticated()
  
              .and()
                  .addFilter(authenticationFilter)
                  .addFilter(authorizationFilter)
  
              // this disables session creation on Spring Security
              .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  
              .and().exceptionHandling().authenticationEntryPoint(new MyAuthenticationEntryPoint());
      }
  
      ...
  
  }
  </code></pre>
  
  <p><strong>MyAuthenticationEntryPoint</strong> </p>
  
  <pre><code>@Component
  public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
  
      private final Logger logger = LoggerFactory.getLogger(MyAuthenticationEntryPoint.class);
  
      @Override
      public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
              AuthenticationException e) {
          logger.debug("Pre-authenticated entry point called. Rejecting access");
          List&lt;Message&gt; errorMessagesList = Arrays.asList(new Message("Unauthorized access"));
          CommonErrorResponse commonErrorResponse =
                  new CommonErrorResponse(errorMessagesList, HttpServletResponse.SC_UNAUTHORIZED);
          try {
              String json = Util.objectToJsonString(commonErrorResponse);
              httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
              httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
              httpServletResponse.setCharacterEncoding(StandardCharsets.UTF_8.toString());
              httpServletResponse.getWriter().write(json);
          } catch (Exception e1) {
              logger.error("Unable to process json response: " + e1.getMessage());
          }
      }
  
  }
  </code></pre>
  
  <p><strong>Swagger Configuration</strong></p>
  
  <pre><code>@EnableSwagger2
  @Configuration
  @Import(BeanValidatorPluginsConfiguration.class)
  public class SwaggerConfig {
  
      @Bean
      public Docket api() {
          return new Docket(DocumentationType.SWAGGER_2).apiInfo(metadata())
                  .select()
                  .apis(RequestHandlerSelectors.basePackage("com.iyotbihagay.controller"))
                  .paths(PathSelectors.any())
                  .build();
      }
  
      private ApiInfo metadata() {
          return new ApiInfoBuilder().title("Iyot Bihagay API Documentation")
                  .description("API documentation for Iyot Bihagay REST Services.").version("1.6.9").build();
      }
  
  }
  </code></pre>
  
  <p>I think it is possible with springfox as I can see it in other like the .net version.</p>
  
  <p>Hope someone could share light to this, on how to secure Swagger UI (springfox-swagger2).</p>
  
  <p>By the way, I am using JWT for my APIs and it is working.<br>
  In relation to swagger, it is working if I set it to <code>permitAll()</code>.<br>
  It does not work if I change it to <code>authenticated()</code>.<br>
  If it works with <code>authenticated()</code>, I will try to apply role/authority checks.</p>
  
  <p>Thanks!</p>