【问题标题】:Secure Springfox Swagger2 UI安全 Springfox Swagger2 UI
【发布时间】:2019-01-27 04:56:52
【问题描述】:

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

但所有拥有该网址的人都可以访问它。

我希望它不是每个人都可以访问的,并且有一个登录屏幕(基本身份验证或谷歌身份验证)真的很棒。

我一直在浏览互联网,但似乎找不到特定于 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(或作为一个整体)只能被所有经过身份验证的用户访问(目前,稍后将基于角色)。

我不确定是否需要在 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());
        }
    }

}

Swagger 配置

@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,它正在工作。
关于招摇,如果我将它设置为permitAll(),它就可以工作。
如果我将其更改为authenticated(),它将不起作用。
如果它适用于authenticated(),我将尝试应用角色/权限检查。

谢谢!

【问题讨论】:

    标签: spring-boot spring-security swagger-ui springfox


    【解决方案1】:

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

    @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

    【讨论】:

    • 谢谢老哥,我试过了,还是不行。只有permitAll() 有效。 authenticated()hasAnyAuthority() 没有。我不知道我是否需要更改 swagger 配置中的某些内容才能使其正常工作。
    猜你喜欢
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多