简体   繁体   中英

Secure Springfox Swagger2 UI

I am using springfox swagger2 and it is working right.
It was just a basic setup/configuration as I am really new with swagger.

But it is accessible to all who have the url.

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.

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).

Update

I can access swagger-ui.html if I set this .antMatchers("/swagger-ui.html**").permitAll() in SecurityConfig class.

But if I change it to .authenticated() , it won't and I am getting the 401 error I set:

{"timestamp":"2018-09-03T06:06:37.882Z","errorCode":401,"errorMessagesList":[{"message":"Unauthorized access"}]}

It seems it hits my authentication entry point. If I can only make swagger-ui.html (or swagger as a whole) be accessible only to all authenticated users (for now, and will be based on roles later on).

I am not sure if I need to add some security configuration on SwaggerConfig.java since I only need to make swagger-ui.html available to authenticated users (or specific roles/authority).

Dependency (pom.xml):

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

Security Configuration class

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

    ...

}

MyAuthenticationEntryPoint

@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<Message> 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());
        }
    }

}

Swagger Configuration

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

}

I think it is possible with springfox as I can see it in other like the .net version.

Hope someone could share light to this, on how to secure Swagger UI (springfox-swagger2).

By the way, I am using JWT for my APIs and it is working.
In relation to swagger, it is working if I set it to permitAll() .
It does not work if I change it to authenticated() .
If it works with authenticated() , I will try to apply role/authority checks.

Thanks!

Add spring security to your project, create "DEVELOPER_ROLE" and a user with that role, then configure your web security, will looks something like this:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

    //swagger-ui resources
    private static final String[] DEVELOPER_WHITELIST = {"/swagger-resources/**", "/swagger-ui.html", "/v2/api-docs"};
    //site resources
    private static final String[] AUTH_HTTP_WHITELIST = {"/path1", "/path2"}; // allowed
    private static final String LOGIN_URL = "/login.html"; // define login page
    private static final String DEFAULT_SUCCESS_URL = "/index.html"; // define landing page after successful login 
    private static final String FAILURE_URL = "/loginFail.html"; // define failed login page/path

    @Override
    protected void configure(final HttpSecurity http) throws Exception {

        http
                .authorizeRequests()
                .antMatchers(AUTH_HTTP_WHITELIST).permitAll()
                .antMatchers(DEVELOPER_WHITELIST).hasRole("DEVELOPER") // for role "DEVELOPER_ROLE"
                .anyRequest()..authenticated()
                .and()
                .formLogin()
                .loginPage(LOGIN_URL)
                .defaultSuccessUrl(DEFAULT_SUCCESS_URL)
                .failureUrl(FAILURE_URL)
                .permitAll()
                .and()
                .logout()
                .logoutSuccessUrl(LOGIN_URL)
                .permitAll();
    }

}

Here is tutorial with samples: https://www.baeldung.com/spring-security-authentication-and-registration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM