如何在“ ../v2/api-docs”json生成的文件中启用SecurityDefinitions

时间:2018-08-20 10:27:21

标签: swagger jhipster swagger-codegen springfox

我想使用swagger客户端生成器,并从jHipster应用程序中输入“ ../v2/api-docs”生成的json。问题在于没有安全性定义,生成的代码将无法工作。 JWT令牌未添加到API请求,该代码未经身份验证即生成。 http://petstore.swagger.io/v2/swagger.json示例具有安全性和安全性定义。在哪里修改/配置jhipster应用程序,以便在json文件中生成安全性和安全性定义? {我手动将安全性和安全性定义添加到json文件中,然后生成的代码可以正常工作,并且在jHipster应用程序中启用了JWT,但是我不想每次API更改时都编辑文件...} securityDefinitions“和” security“:[{” petstore_auth“:[” write:pets“,” read:pets“]}]]部分从jHipster应用程序生成的json文件中完全丢失,即使启用并需要JWT发出API请求。

3 个答案:

答案 0 :(得分:2)

迟到总比不到好。

JHipster应用程序依赖于JHipster Framework,后者负责springfox的Docket配置。

JHipster Framework的SwaggerAutoConfiguration customizes the springfox Docket,其中每个SwaggerCustomizer bean都已在应用程序中注册。 JHipster将其own swagger customizer注册为默认文案配置。

这就是说,您需要添加自己的摘要定制器,以便在springfox的摘要中包含所需的安全定义和任何其他附加配置。为此,您需要:

在现有的配置包中创建招摇狂的动作。在其中创建一个CustomSwaggerConfig类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CustomSwaggerConfig {

    public CustomSwaggerConfig() {
    }

    @Bean
    public ApplicationSwaggerCustomizer applicationSwaggerCustomizer() {
        return new ApplicationSwaggerCustomizer();
    }

}

并创建ApplicationSwaggerCustomizer类:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.github.jhipster.config.apidoc.customizer.SwaggerCustomizer;
import springfox.documentation.spring.web.plugins.Docket;

public class ApplicationSwaggerCustomizer implements SwaggerCustomizer {

    private final Logger log = LoggerFactory.getLogger(ApplicationSwaggerCustomizer.class);

    public ApplicationSwaggerCustomizer() {
    }

    @Override
    public void customize(Docket docket) {
        log.debug("Customizing springfox docket...");
        // TODO Here you can add all the configurations to the docket
    }

}

现在您可以添加任何其他文案配置。

答案 1 :(得分:0)

您可以使用以下方法克隆默认实现:

package <YOUR_PACKAGE>;

import static io.github.jhipster.config.JHipsterConstants.SPRING_PROFILE_SWAGGER;
import static springfox.documentation.builders.PathSelectors.regex;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

import io.github.jhipster.config.JHipsterProperties;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.ApiKeyVehicle;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Springfox Swagger configuration.
 * <p>
 * Warning! When having a lot of REST endpoints, Springfox can become a performance issue.
 * In that case, you can use the "no-swagger" Spring profile, so that this bean is ignored.
 */
@Configuration
@Profile(SPRING_PROFILE_SWAGGER)
@EnableSwagger2
public class SwaggerConfiguration {

    static final String STARTING_MESSAGE = "Starting Swagger with JWT";
    static final String STARTED_MESSAGE = "Started Swagger with JWT in {} ms";
    static final String MANAGEMENT_TITLE_SUFFIX = "Management API";
    static final String MANAGEMENT_GROUP_NAME = "management";
    static final String MANAGEMENT_DESCRIPTION = "Management endpoints documentation";
    public static final String AUTHORIZATION_HEADER = "Authorization";

    private final Logger log = LoggerFactory.getLogger(SwaggerConfiguration.class);

    private final JHipsterProperties.Swagger properties;

    public SwaggerConfiguration(JHipsterProperties jHipsterProperties) {
        this.properties = jHipsterProperties.getSwagger();
    }

    /**
     * Springfox configuration for the API Swagger with JWT docs.
     *
     * @return the Swagger Springfox configuration
     */
    @Bean
    public Docket swaggerSpringfoxApiDocket() {
        log.debug(STARTING_MESSAGE);
        StopWatch watch = new StopWatch();
        watch.start();

        Docket docket = createDocket();

        Contact contact = new Contact(
                properties.getContactName(),
                properties.getContactUrl(),
                properties.getContactEmail()
            );

        ApiInfo apiInfo = new ApiInfo(
            properties.getTitle(),
            properties.getDescription(),
            properties.getVersion(),
            properties.getTermsOfServiceUrl(),
            contact,
            properties.getLicense(),
            properties.getLicenseUrl(),
            new ArrayList<>()
        );

        docket.host(properties.getHost())
            .protocols(new HashSet<>(Arrays.asList(properties.getProtocols())))
            .securitySchemes(Arrays.asList((apiKey())))
            .securityContexts(Arrays.asList(
                SecurityContext.builder()
                    .securityReferences(
                        Arrays.asList(SecurityReference.builder()
                            .reference("JWT")
                            .scopes(new AuthorizationScope[0])
                            .build()
                        )
                    )
                    .build())
            )
            .apiInfo(apiInfo)
            .useDefaultResponseMessages(properties.isUseDefaultResponseMessages())
            .forCodeGeneration(true)
            .directModelSubstitute(ByteBuffer.class, String.class)
            .genericModelSubstitutes(ResponseEntity.class)
            .ignoredParameterTypes(Pageable.class)
            .select()
            .paths(regex(properties.getDefaultIncludePattern()))
            .build();

        watch.stop();
        log.debug(STARTED_MESSAGE, watch.getTotalTimeMillis());
        return docket;
    }

    /**
     * Springfox configuration for the management endpoints (actuator) Swagger docs.
     *
     * @param appName               the application name
     * @param managementContextPath the path to access management endpoints
     * @return the Swagger Springfox configuration
     */
    @Bean
    @ConditionalOnMissingBean(name = "swaggerSpringfoxManagementDocket")
    public Docket swaggerSpringfoxManagementDocket(@Value("${spring.application.name:application}") String appName,
        @Value("${management.endpoints.web.base-path}") String managementContextPath) {

        ApiInfo apiInfo = new ApiInfo(
            StringUtils.capitalize(appName) + " " + MANAGEMENT_TITLE_SUFFIX,
            MANAGEMENT_DESCRIPTION,
            properties.getVersion(),
            "",
            ApiInfo.DEFAULT_CONTACT,
            "",
            "",
            new ArrayList<>()
        );

        return createDocket()
            .apiInfo(apiInfo)
            .useDefaultResponseMessages(properties.isUseDefaultResponseMessages())
            .groupName(MANAGEMENT_GROUP_NAME)
            .host(properties.getHost())
            .protocols(new HashSet<>(Arrays.asList(properties.getProtocols())))
            .securitySchemes(Arrays.asList((apiKey())))
            .securityContexts(Arrays.asList(
                SecurityContext.builder()
                    .securityReferences(
                        Arrays.asList(SecurityReference.builder()
                            .reference("JWT")
                            .scopes(new AuthorizationScope[0])
                            .build()
                        )
                    )
                    .build())
            )
            .forCodeGeneration(true)
            .directModelSubstitute(ByteBuffer.class, String.class)
            .genericModelSubstitutes(ResponseEntity.class)
            .ignoredParameterTypes(Pageable.class)
            .select()
            .paths(regex(managementContextPath + ".*"))
            .build();
    }

    protected Docket createDocket() {
        return new Docket(DocumentationType.SWAGGER_2);
    }

    private ApiKey apiKey() {
        return new ApiKey("JWT", AUTHORIZATION_HEADER, ApiKeyVehicle.HEADER.getValue()); 
    }

} // END

答案 2 :(得分:-1)

一开始我遇到了和你类似的问题,我搜索了你的帖子。 但是我的项目使用 .net core,从下面的 url 我找到了一个解决方案。 如果您的问题没有得到解决,希望它可以帮助您。 https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements