繁体   English   中英

安全的Springfox Swagger2 UI

[英]Secure Springfox Swagger2 UI

我正在使用springfox swagger2,它工作正常。
这只是一个基本的设置/配置,因为我真的是措手不及。

但是所有拥有该URL的人都可以使用它。

我希望每个人都不能访问它,并拥有一个登录屏幕(基本身份验证或Google身份验证)确实很棒。

我一直在浏览互联网,但似乎找不到特定于springfox-swagger2的内容。 我可以找到一些,但似乎它适用于.Net(基于C#的示例)。

更新

如果在SecurityConfig类中设置此.antMatchers("/swagger-ui.html**").permitAll() ,则可以访问swagger-ui.html

但是,如果我将其更改为.authenticated() ,则不会,并且会收到我设置的401错误:

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

看来它击中了我的身份验证入口点。 如果我只能使swagger-ui.html (或整个swagger)仅对所有经过身份验证的用户可用(目前,并将基于以后的角色)。

我不确定是否需要在SwaggerConfig.java上添加一些安全配置,因为我只需要使swagger-ui.html对经过身份验证的用户(或特定角色/权限)可用。

依赖关系(pom.xml):

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

安全配置类

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

}

昂首阔步的配置

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

}

我认为springfox是可能的,因为我可以在其他.net版本中看到它。

希望有人可以就如何保护Swagger UI(springfox-swagger2)达成共识。

顺便说一句,我正在为我的API使用JWT,它正在工作。
关于swagger,如果将其设置为permitAll() ,则可以正常工作。
如果将其更改为authenticated()它将不起作用。
如果它与authenticated() ,我将尝试应用角色/权限检查。

谢谢!

将spring安全性添加到您的项目中,创建“ DEVELOPER_ROLE”和具有该角色的用户,然后配置您的Web安全性,将如下所示:

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

}

这是带有示例的教程: https : //www.baeldung.com/spring-security-authentication-and-registration

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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