Spring boot 安全Springfox Swigger2用户界面

Spring boot 安全Springfox Swigger2用户界面,spring-boot,spring-security,swagger-ui,springfox,Spring Boot,Spring Security,Swagger Ui,Springfox,我正在使用springfox Swagger 2,它工作正常。 这只是一个基本的设置/配置,因为我对招摇过市很陌生 但所有拥有url的人都可以访问它 我希望它不是每个人都可以访问,并且有一个登录屏幕(基本身份验证或谷歌身份验证)真的很棒 我一直在网上搜索,但似乎找不到springfox-Swagger 2的特定内容。我可以找到一些,但似乎是针对.Net的(基于C#的示例) 更新 如果在SecurityConfig类中设置此.antMatchers(“/swagger ui.html**”).pe

我正在使用springfox Swagger 2,它工作正常。
这只是一个基本的设置/配置,因为我对招摇过市很陌生

但所有拥有url的人都可以访问它

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

我一直在网上搜索,但似乎找不到springfox-Swagger 2的特定内容。我可以找到一些,但似乎是针对.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>
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());
        }
    }

}
我认为使用springfox是可能的,因为我可以在其他版本(如.net版本)中看到这一点

希望有人能分享这方面的信息,关于如何保护Swagger UI(springfox-Swagger 2)

顺便说一句,我正在将JWT用于我的API,它正在工作。
关于swagger,如果我将其设置为
permitAll()

如果我将其更改为
authenticated()

如果它与
authenticated()
一起工作,我将尝试应用角色/权限检查


谢谢

将spring安全性添加到您的项目中,创建“开发者角色”和具有该角色的用户,然后配置您的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();
    }

}
以下是示例教程:

谢谢,兄弟,我试过了,但没用。只有
permitAll()
起作用
authenticated()
hasAnyAuthority()
没有。我不知道我是否需要改变一些在招摇配置只是为了使这项工作。
@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();
    }

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

}