Swagger 如何在";中启用SecurityDefinitions/v2/api文件“;json生成的文件

Swagger 如何在";中启用SecurityDefinitions/v2/api文件“;json生成的文件,swagger,jhipster,swagger-codegen,springfox,Swagger,Jhipster,Swagger Codegen,Springfox,我想使用swagger客户端生成器,并提供jHipster应用程序中“./v2/api docs”生成的json。问题是,如果没有安全定义,生成的代码将无法工作。JWT令牌不会添加到API请求中,代码是在没有身份验证的情况下生成的。该示例具有security和securityDefinitions。在何处修改/配置jhipster应用程序,以便在json文件中生成安全和安全定义?{我手动将安全性和安全性定义添加到json文件中,然后生成的代码工作,jHipster应用程序中启用了JWT,但我不想

我想使用swagger客户端生成器,并提供jHipster应用程序中“./v2/api docs”生成的json。问题是,如果没有安全定义,生成的代码将无法工作。JWT令牌不会添加到API请求中,代码是在没有身份验证的情况下生成的。该示例具有security和securityDefinitions。在何处修改/配置jhipster应用程序,以便在json文件中生成安全和安全定义?{我手动将安全性和安全性定义添加到json文件中,然后生成的代码工作,jHipster应用程序中启用了JWT,但我不想在每次API更改时编辑该文件。}“securityDefinitions”和“security”:[{“petstore_auth”:[“write:pets”,“read:pets”]}]jHipster应用程序生成的json文件中完全没有节,即使启用了JWT并且需要发出API请求

您可以通过以下方式克隆默认实现:

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
包;
导入静态io.github.jhipster.config.JHipsterConstants.SPRING\u PROFILE\u SWAGGER;
导入静态springfox.documentation.builders.PathSelectors.regex;
导入java.nio.ByteBuffer;
导入java.util.ArrayList;
导入java.util.array;
导入java.util.HashSet;
导入org.slf4j.Logger;
导入org.slf4j.LoggerFactory;
导入org.springframework.beans.factory.annotation.Value;
导入org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
导入org.springframework.context.annotation.Bean;
导入org.springframework.context.annotation.Configuration;
导入org.springframework.context.annotation.Profile;
导入org.springframework.data.domain.Pageable;
导入org.springframework.http.ResponseEntity;
导入org.springframework.util.StopWatch;
导入org.springframework.util.StringUtils;
导入io.github.jhipster.config.JHipsterProperties;
导入springfox.documentation.service.apinfo;
导入springfox.documentation.service.ApiKey;
导入springfox.documentation.service.AuthorizationScope;
导入springfox.documentation.service.Contact;
导入springfox.documentation.service.SecurityReference;
导入springfox.documentation.spi.DocumentationType;
导入springfox.documentation.spi.service.contexts.SecurityContext;
导入springfox.documentation.spring.web.plugins.Docket;
导入springfox.documentation.swagger.web.ApiKeyVehicle;
导入springfox.documentation.swagger 2.annotations.enableSawagger 2;
/**
*Springfox大摇大摆的配置。
*
*警告!当有很多REST端点时,Springfox可能会成为性能问题。
*在这种情况下,您可以使用“no-swagger”Spring配置文件,以便忽略此bean。
*/
@配置
@剖面图(弹簧剖面图)
@使能招摇过市2
公共类招摇过市配置{
静态最终字符串开始\u MESSAGE=“用JWT开始招摇过市”;
静态最终字符串STARTED_MESSAGE=“STARTED Swagger with JWT in{}ms”;
静态最终字符串管理\u TITLE\u SUFFIX=“管理API”;
静态最终字符串管理\u组\u NAME=“管理”;
静态最终字符串管理\u DESCRIPTION=“管理端点文档”;
公共静态最终字符串授权\u HEADER=“AUTHORIZATION”;
私有最终记录器log=LoggerFactory.getLogger(SwaggerConfiguration.class);
私人房地产;招摇过市的房地产;
公共虚张声势配置(JHIPSterpreproperties JHIPSterpreproperties){
this.properties=jHipsterProperties.getSwagger();
}
/**
*Springfox配置用于使用JWT文档的API招摇过市。
*
*@return-the-Swagger-Springfox配置
*/
@豆子
公众卷宗大摇大摆{
log.debug(启动_消息);
秒表=新秒表();
watch.start();
Docket Docket=createDocket();
联系人=新联系人(
properties.getContactName(),
properties.getContactUrl(),
properties.getContactEmail()
);
apinfo apinfo=新的apinfo(
properties.getTitle(),
properties.getDescription(),
properties.getVersion(),
properties.getTermsOfServiceUrl(),
联系方式,
properties.getLicense(),
properties.getLicenseUrl(),
新ArrayList()
);
docket.host(properties.getHost())
.protocols(新的HashSet(Arrays.asList(properties.getProtocols()))
.securitySchemes(Arrays.asList((apiKey()))
.SecurityContext(Arrays.asList(
SecurityContext.builder()
.证券参考(
Arrays.asList(SecurityReference.builder()
.参考(“JWT”)
.scopes(新授权范围[0])
.build()
)
)
.build())
)
.apinfo(apinfo)
.useDefaultResponseMessages(属性.isUseDefaultResponseMessages())
.forCodeGeneration(真)
.directModelSubstitute(ByteBuffer.class,String.class)
.genericModelSubstitutes(ResponseEntity.class)
.ignoredParameterTypes(Pageable.class)
.选择()
.path(regex(properties.getDefaultIncludePattern()))
.build();
看,停;
log.debug(启动_消息,watch.getTotalItemillis());
返回摘要;
}
/**
*管理端点(执行器)的Springfox配置Swagger文档。
*
*@param appName应用程序名称
*@param managementContextPath访问管理端点的路径
*@return-the-Swagger-Springfox配置
*/
@豆子
@ConditionalOnMissingBean(name=“SwiggerSpringFoxManagementDocket”)
公开诉讼
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();
    }

}
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
    }

}