Spring boot Spring Boot中具有安全性的Swagger配置示例

Spring boot Spring Boot中具有安全性的Swagger配置示例,spring-boot,swagger,Spring Boot,Swagger,有人举了一个使用spring boot的招摇过市安全性的例子 我的摘要配置如下: @Bean public Docket userApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(Predicates.not(PathSelectors.regex("/error.*"))) .paths(

有人举了一个使用spring boot的招摇过市安全性的例子

我的摘要配置如下:

@Bean
public Docket userApi() {
    return new Docket(DocumentationType.SWAGGER_2)
    .select()
    .apis(RequestHandlerSelectors.any())
    .paths(Predicates.not(PathSelectors.regex("/error.*")))
    .paths(PathSelectors.any())
    .build()
    .apiInfo(metaData());

}

要使用安全性配置swagger,您应该如下设置SecurityContext:

private final TypeResolver typeResolver;

// constructor
public SwaggerConfig(TypeResolver typeResolver) {
    this.typeResolver = typeResolver;
}
@Bean
public Docket apiBatch() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("path.to.package"))
            .paths(PathSelectors.any())
            .build()
            .securitySchemes(Lists.newArrayList(apiKey()))
            .securityContexts(Collections.singletonList(securityContext()))
            .apiInfo(apiInfo());
}

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title(title)
            .description(description)
            .version(version)
            .build();
}

/**
 * add as header the Authorization header
 *
 * @return
 */
private ApiKey apiKey() {
    return new ApiKey("apiKey", "Authorization", "header");
}

/**
 * demand the authorization for access on /api/v1/**
 *
 * @return
 */
private SecurityContext securityContext() {
    return SecurityContext.builder().securityReferences(defaultAuth())
            .forPaths(PathSelectors.regex("/api/v1.*")).build();
}

private List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope = new AuthorizationScope(
            "global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return Collections.singletonList(new SecurityReference("apiKey",
            authorizationScopes));
}

private AlternateTypeRule getAlternateTypeRule(Type sourceType, Type sourceGenericType,
                                               Type targetType, Type targetGenericType) {
    return AlternateTypeRules.newRule(typeResolver.resolve(sourceType, sourceGenericType),
            typeResolver.resolve(targetType, targetGenericType));
}
编辑 我已经添加了fasterxml同学库编译组的TypeResolver属性:“com.fasterxml”,名称:“classmate”,版本:“1.3.1”


请注意,SwaggerConfig是配置类名

Yes!您需要添加类型为TypeResolver的属性并使用构造函数自动连接您可以看到上面的更新和类型类?当您创建getAlternateTypeRule函数时,您使用类型sourceType,但导入类型是什么?啊,很抱歉,它来自java.lang。reflect@Abdelhani鲁西,你有我可以联系你的电子邮件吗?