处理Swagger3问题

This commit is contained in:
2023-10-16 16:30:47 +08:00
parent 1b20b0c34c
commit cc567b98e6
2 changed files with 323 additions and 303 deletions

View File

@ -1,141 +1,161 @@
package com.jnssd.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.OAuthBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
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.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.SecurityConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* <h3>spring-boot-openapi</h3>
* <p></p>
*
* @author zxj
* @since 2023-10-12 17:13:09
*/
@Configuration
@EnableSwagger2
@EnableOpenApi
public class SwaggerConfig {
private final String[] securitySchemeNames = {"ApiKey模式", "basicAuth模式", "oauth2的Password模式", "oauth2的authorization_code模式", "oauth2的implicit模式", "oauth2的clientCredentials模式"};
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
// 扫描特定包
// 扫描所有有注解的api用这种方式更灵活
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//.apis(RequestHandlerSelectors.any())
.apis(RequestHandlerSelectors.basePackage("com.jnssd")).paths(PathSelectors.any()).build().securitySchemes(initSecuritySchemeList()).securityContexts(Collections.singletonList(securityContext()));
}
public ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Swagger项目测试").description("novel项目接口文档").build();
}
public List<SecurityScheme> initSecuritySchemeList() {
List<SecurityScheme> list = new ArrayList<>();
list.add(securitySchemeBasicAuth());
list.add(securitySchemeApiKey());
// oauth2下的几个模式配置
// 1. 密码模式
list.add(securitySchemeOAuth2Password());
// 2. 客户端模式
list.add(securitySchemeOAuth2ClientCredentials());
// 3. 授权码模式
list.add(securitySchemeOAuth2AuthorizationCode());
// 4. 简化模式
list.add(securitySchemeOAuth2Implicit());
return list;
}
// ApiKey模式
private SecurityScheme securitySchemeApiKey() {
return new ApiKey("ApiKey模式", "Authorization", ApiKeyVehicle.HEADER.getValue());
}
// basicAuth模式
private SecurityScheme securitySchemeBasicAuth() {
return new BasicAuth("basicAuth模式");
}
// oauth2下面的password模式
private SecurityScheme securitySchemeOAuth2Password() {
List<GrantType> grantTypes = new ArrayList<>();
grantTypes.add(new ResourceOwnerPasswordCredentialsGrant("/oauth/token"));
return new OAuthBuilder().name("oauth2的Password模式").scopes(scopes()).grantTypes(grantTypes).build();
}
// oauth2下面的authorization_code模式
private SecurityScheme securitySchemeOAuth2AuthorizationCode() {
List<GrantType> grantTypes = new ArrayList<>();
TokenRequestEndpoint tokenRequestEndpoint = new TokenRequestEndpoint("/oauth/authorize", "", "");
TokenEndpoint tokenEndpoint = new TokenEndpoint("/oauth/token", "token");
grantTypes.add(new AuthorizationCodeGrant(tokenRequestEndpoint, tokenEndpoint));
return new OAuthBuilder().name("oauth2的authorization_code模式").scopes(scopes()).grantTypes(grantTypes).build();
}
// oauth2下面的implicit模式
private SecurityScheme securitySchemeOAuth2Implicit() {
List<GrantType> grantTypes = new ArrayList<>();
ImplicitGrant implicitGrant = new ImplicitGrant(new LoginEndpoint("/oauth/authorize"), "token");
grantTypes.add(implicitGrant);
return new OAuthBuilder().name("oauth2的implicit模式").scopes(scopes()).grantTypes(grantTypes).build();
}
// oauth2下面的ClientCredentials模式
private SecurityScheme securitySchemeOAuth2ClientCredentials() {
List<GrantType> grantTypes = new ArrayList<>();
grantTypes.add(new ClientCredentialsGrant("/oauth/token"));
return new OAuthBuilder().name("oauth2的clientCredentials模式").scopes(scopes()).grantTypes(grantTypes).build();
}
private SecurityContext securityContext() {
List<SecurityReference> list = new ArrayList<>();
Arrays.stream(securitySchemeNames).forEach(s -> list.add(new SecurityReference(s, new AuthorizationScope[0])));
return SecurityContext.builder().operationSelector(operationContext -> {
System.out.println("operationContext" + operationContext);
// 除了get方法其他方法都要校验
// return !operationContext.httpMethod().name().equals("GET");
// 通过地址模糊匹配
AntPathMatcher pathMatcher = new AntPathMatcher();
String path = operationContext.requestMappingPattern();
return pathMatcher.match("/menu/**", path) || pathMatcher.match("/user/**", path);
}).securityReferences(list).build();
}
private List<AuthorizationScope> scopes() {
List<AuthorizationScope> list = new ArrayList<>();
list.add(new AuthorizationScope("read_scope", "Grants read access"));
list.add(new AuthorizationScope("write_scope", "Grants write access"));
list.add(new AuthorizationScope("admin_scope", "Grants read write and delete access"));
return list;
}
@Bean
public SecurityConfiguration security() {
return SecurityConfigurationBuilder.builder().clientId("").clientSecret("").realm("*").appName("").scopeSeparator("").useBasicAuthenticationWithAccessCodeGrant(false).build();
}
}
// package com.jnssd.config;
//
// import org.springframework.context.annotation.Bean;
// import org.springframework.context.annotation.Configuration;
// import org.springframework.util.AntPathMatcher;
// import springfox.documentation.builders.ApiInfoBuilder;
// import springfox.documentation.builders.OAuthBuilder;
// import springfox.documentation.builders.PathSelectors;
// import springfox.documentation.builders.RequestHandlerSelectors;
// import springfox.documentation.oas.annotations.EnableOpenApi;
// import springfox.documentation.service.*;
// 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;
//
// import java.util.ArrayList;
// import java.util.Arrays;
// import java.util.Collections;
// import java.util.List;
//
// /**
// * <h3>spring-boot-openapi</h3>
// * <p></p>
// *
// * @author zxj
// * @since 2023-10-12 17:13:09
// */
// @Configuration
// @EnableSwagger2
// @EnableOpenApi
// public class SwaggerConfig {
//
// private final String[] securitySchemeNames = {"ApiKey模式", "basicAuth模式", "oauth2的Password模式", "oauth2的authorization_code模式", "oauth2的implicit模式", "oauth2的clientCredentials模式"};
//
//
// @Bean
// public Docket api() {
// return new Docket(DocumentationType.SWAGGER_2)
// .apiInfo(apiInfo()).select()
// // 扫描特定包
// // 扫描所有有注解的api用这种方式更灵活
// // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// //.apis(RequestHandlerSelectors.any())
// .apis(RequestHandlerSelectors.basePackage("com.jnssd"))
// .paths(PathSelectors.any())
// .build()
// .securitySchemes(initSecuritySchemeList())
// .securityContexts(Collections.singletonList(securityContext()));
// }
//
// public ApiInfo apiInfo() {
// return new ApiInfoBuilder()
// .title("Swagger项目测试")
// .description("novel项目接口文档")
// .build();
// }
//
//
// /**
// * 初始化安全方案
// *
// * @return
// */
// public List<SecurityScheme> initSecuritySchemeList() {
// List<SecurityScheme> list = new ArrayList<>();
// list.add(securitySchemeBasicAuth());
// list.add(securitySchemeApiKey());
//
// // oauth2下的几个模式配置
// // 1. 密码模式
// list.add(securitySchemeOAuth2Password());
// // 2. 客户端模式
// list.add(securitySchemeOAuth2ClientCredentials());
// // 3. 授权码模式
// list.add(securitySchemeOAuth2AuthorizationCode());
// // 4. 简化模式
// list.add(securitySchemeOAuth2Implicit());
// return list;
// }
//
// // ApiKey模式
// private SecurityScheme securitySchemeApiKey() {
// return new ApiKey("ApiKey模式", "Authorization", ApiKeyVehicle.HEADER.getValue());
// }
//
// // basicAuth模式
// private SecurityScheme securitySchemeBasicAuth() {
// return new BasicAuth("basicAuth模式");
// }
//
// // oauth2下面的password模式
// private SecurityScheme securitySchemeOAuth2Password() {
// List<GrantType> grantTypes = new ArrayList<>();
// grantTypes.add(new ResourceOwnerPasswordCredentialsGrant("/oauth/token"));
// return new OAuthBuilder().name("oauth2的Password模式").scopes(scopes()).grantTypes(grantTypes).build();
// }
//
// // oauth2下面的authorization_code模式
// private SecurityScheme securitySchemeOAuth2AuthorizationCode() {
// List<GrantType> grantTypes = new ArrayList<>();
// TokenRequestEndpoint tokenRequestEndpoint = new TokenRequestEndpoint("/oauth/authorize", "", "");
// TokenEndpoint tokenEndpoint = new TokenEndpoint("/oauth/token", "token");
// grantTypes.add(new AuthorizationCodeGrant(tokenRequestEndpoint, tokenEndpoint));
// return new OAuthBuilder().name("oauth2的authorization_code模式").scopes(scopes()).grantTypes(grantTypes).build();
// }
//
// // oauth2下面的implicit模式
// private SecurityScheme securitySchemeOAuth2Implicit() {
// List<GrantType> grantTypes = new ArrayList<>();
// ImplicitGrant implicitGrant = new ImplicitGrant(new LoginEndpoint("/oauth/authorize"), "token");
// grantTypes.add(implicitGrant);
// return new OAuthBuilder().name("oauth2的implicit模式").scopes(scopes()).grantTypes(grantTypes).build();
// }
//
// // oauth2下面的ClientCredentials模式
// private SecurityScheme securitySchemeOAuth2ClientCredentials() {
// List<GrantType> grantTypes = new ArrayList<>();
// grantTypes.add(new ClientCredentialsGrant("/oauth/token"));
// return new OAuthBuilder().name("oauth2的clientCredentials模式").scopes(scopes()).grantTypes(grantTypes).build();
// }
//
// /**
// * oauth2访问范围
// *
// * @return
// */
// private List<AuthorizationScope> scopes() {
// List<AuthorizationScope> list = new ArrayList<>();
// list.add(new AuthorizationScope("read_scope", "Grants read access"));
// list.add(new AuthorizationScope("write_scope", "Grants write access"));
// list.add(new AuthorizationScope("admin_scope", "Grants read write and delete access"));
// return list;
// }
//
// /**
// * 配置接口下哪些需要实现安全访问
// * @return
// */
// private SecurityContext securityContext() {
// List<SecurityReference> list = new ArrayList<>();
// // 这里的SecurityReference第一个参数值必须和SecurityScheme的name值一致
// Arrays.stream(securitySchemeNames).forEach(name -> list.add(new SecurityReference(name, new AuthorizationScope[0])));
// return SecurityContext.builder().operationSelector(operationContext -> {
// System.out.println("operationContext" + operationContext);
// // 除了get方法其他方法都要校验
// // return !operationContext.httpMethod().name().equals("GET");
//
// // 通过地址模糊匹配
// AntPathMatcher pathMatcher = new AntPathMatcher();
// String path = operationContext.requestMappingPattern();
// return pathMatcher.match("/menu/**", path) || pathMatcher.match("/user/**", path);
// }).securityReferences(list).build();
// }
// // @Bean
// // public SecurityConfiguration security() {
// // return SecurityConfigurationBuilder.builder().clientId("").clientSecret("").realm("*").appName("").scopeSeparator("").useBasicAuthenticationWithAccessCodeGrant(false).build();
// // }
//
// }

View File

@ -1,162 +1,162 @@
// package com.jnssd.config;
//
// import org.springframework.context.annotation.Bean;
// import org.springframework.context.annotation.Configuration;
// import org.springframework.util.AntPathMatcher;
// import springfox.documentation.builders.ApiInfoBuilder;
// import springfox.documentation.builders.OpenIdConnectSchemeBuilder;
// import springfox.documentation.builders.PathSelectors;
// import springfox.documentation.builders.RequestHandlerSelectors;
// import springfox.documentation.oas.annotations.EnableOpenApi;
// import springfox.documentation.service.*;
// import springfox.documentation.spi.DocumentationType;
// import springfox.documentation.spi.service.contexts.SecurityContext;
// import springfox.documentation.spring.web.plugins.Docket;
//
// import java.util.ArrayList;
// import java.util.Collections;
// import java.util.List;
//
// /**
// * <h3>spring-boot-openapi</h3>
// * <p>配置openapi</p>
// *
// * @author zxj
// * @since 2023-10-13 14:29:58
// */
//
// @Configuration
// @EnableOpenApi
// public class SwaggerOpenApiConfig {
//
// @Bean
// public Docket api() {
// return new Docket(DocumentationType.OAS_30)
// .apiInfo(apiInfo())
// .select()
// // 扫描特定包
// // 扫描所有有注解的api用这种方式更灵活
// // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// //.apis(RequestHandlerSelectors.any())
// .apis(RequestHandlerSelectors.basePackage("com.jnssd"))
// .paths(PathSelectors.any())
// .build()
// .securitySchemes(initSecuritySchemeList())
// .securityContexts(Collections.singletonList(securityContext()));
// }
//
// public ApiInfo apiInfo() {
// return new ApiInfoBuilder()
// .title("Swagger项目测试")
// .description("novel项目接口文档")
// .build();
// }
//
// private List<SecurityScheme> initSecuritySchemeList() {
//
// List<SecurityScheme> list = new ArrayList<>();
// list.add(httpAuthenticationScheme());
// list.add(securitySchemeApiKey());
// list.add(securitySchemeOpenIdConnect());
//
// // 配置oauth2的几种模式
// list.add(securitySchemeOauth2ClientCredentials());
// list.add(securitySchemeOauth2implicit());
// list.add(securitySchemeOauth2Password());
// list.add(securitySchemeOauth2AuthorizationCode());
// return list;
// }
//
// private SecurityScheme httpAuthenticationScheme() {
// return HttpAuthenticationScheme.JWT_BEARER_BUILDER.name("JWT的值").build();
// }
//
// // ApiKey模式
// private SecurityScheme securitySchemeApiKey() {
// return new ApiKey("Authorization授权", "Authorization", "header");
// }
//
// // OpenIdConnect
//
// // return new OpenIdConnectSchemeBuilder()
// // .name("OpenId授权")
// // .description("OpenIdConnect授权配置")
// // .openIdConnectUrl("https://your-openid-connect-url")
// // .build();
// private SecurityScheme securitySchemeOpenIdConnect() {
// // Swagger配置 OpenIdConnect
// return new OpenIdConnectSchemeBuilder()
// .name("OpenIdConnect授权")
// .description("OpenIdConnect授权配置")
// .openIdConnectUrl("https://your-openid-connect-url")
// .build();
// }
//
// // 客户端模式
// private SecurityScheme securitySchemeOauth2ClientCredentials() {
// return OAuth2Scheme.OAUTH2_CLIENT_CREDENTIALS_FLOW_BUILDER
// .name("客户端模式")
// .tokenUrl("/oauth/authorize")
// .scopes(scopes())
// .build();
// }
//
// // 隐式模式
// private SecurityScheme securitySchemeOauth2implicit() {
// return OAuth2Scheme.OAUTH2_IMPLICIT_FLOW_BUILDER
// .name("简化模式")
// .authorizationUrl("/oauth/authorize")
// .scopes(scopes())
// .build();
// }
//
// // 密码模式
// private SecurityScheme securitySchemeOauth2Password() {
// return OAuth2Scheme.OAUTH2_PASSWORD_FLOW_BUILDER
// .name("密码模式")
// .tokenUrl("/oauth/token")
// .scopes(scopes())
// .build();
// }
//
// // 授权码模式
// private SecurityScheme securitySchemeOauth2AuthorizationCode() {
// return OAuth2Scheme.OAUTH2_AUTHORIZATION_CODE_FLOW_BUILDER
// .name("授权码模式")
// .authorizationUrl("/oauth/authorize")
// .tokenUrl("/oauth/token")
// .scopes(scopes())
// .build();
// }
//
// private List<AuthorizationScope> scopes() {
// List<AuthorizationScope> list = new ArrayList<>();
// list.add(new AuthorizationScope("read_scope", "Grants read access"));
// list.add(new AuthorizationScope("write_scope", "Grants write access"));
// list.add(new AuthorizationScope("admin_scope", "Grants read write and delete access"));
// return list;
// }
//
// private SecurityContext securityContext() {
// return SecurityContext.builder()
// .securityReferences(defaultAuth())
// .operationSelector(operationContext -> {
// System.out.println("operationContext" + operationContext);
// // 除了get方法其他方法都要校验
// // return !operationContext.httpMethod().name().equals("GET");
//
// // 通过地址模糊匹配
// AntPathMatcher pathMatcher = new AntPathMatcher();
// String path = operationContext.requestMappingPattern();
// return pathMatcher.match("/menu/**", path) || pathMatcher.match("/user/**", path);
// })
// .build();
// }
//
// private List<SecurityReference> defaultAuth() {
// AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
// AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
// authorizationScopes[0] = authorizationScope;
// return Collections.singletonList(new SecurityReference("密码模式", authorizationScopes));
// }
// }
package com.jnssd.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.OpenIdConnectSchemeBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* <h3>spring-boot-openapi</h3>
* <p>配置openapi</p>
*
* @author zxj
* @since 2023-10-13 14:29:58
*/
@Configuration
@EnableOpenApi
public class SwaggerOpenApiConfig {
private final String[] securitySchemeNames = {"JWT模式", "ApiKey模式", "OIDC模式", "oauth2的Password模式", "oauth2的authorization_code模式", "oauth2的implicit模式", "oauth2的clientCredentials模式"};
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
// 扫描特定包
// 扫描所有有注解的api用这种方式更灵活
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//.apis(RequestHandlerSelectors.any())
.apis(RequestHandlerSelectors.basePackage("com.jnssd"))
.paths(PathSelectors.any())
.build()
.securitySchemes(initSecuritySchemeList())
.securityContexts(Collections.singletonList(securityContext()));
}
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger项目测试")
.description("novel项目接口文档")
.build();
}
private List<SecurityScheme> initSecuritySchemeList() {
List<SecurityScheme> list = new ArrayList<>();
list.add(httpAuthenticationScheme());
// list.add(securitySchemeApiKey());
// list.add(securitySchemeOpenIdConnect());
//
// // 配置oauth2的几种模式
// list.add(securitySchemeOauth2ClientCredentials());
// list.add(securitySchemeOauth2implicit());
// list.add(securitySchemeOauth2Password());
// list.add(securitySchemeOauth2AuthorizationCode());
return list;
}
// basic模式或者JWT模式
private SecurityScheme httpAuthenticationScheme() {
// 之前的basic模式
// return HttpAuthenticationScheme.BASIC_AUTH_BUILDER.name("basic模式").build();
return HttpAuthenticationScheme.JWT_BEARER_BUILDER.name("JWT模式").build();
}
// ApiKey模式
private SecurityScheme securitySchemeApiKey() {
return new ApiKey("ApiKey模式", "Authorization", "header");
}
// OpenIdConnect
// return new OpenIdConnectSchemeBuilder()
// .name("OpenId授权")
// .description("OpenIdConnect授权配置")
// .openIdConnectUrl("https://your-openid-connect-url")
// .build();
private SecurityScheme securitySchemeOpenIdConnect() {
// Swagger配置 OpenIdConnect
return new OpenIdConnectSchemeBuilder()
.name("OpenIdConnect授权")
.description("OpenIdConnect授权配置")
.openIdConnectUrl("https://your-openid-connect-url")
.build();
}
// oauth2下面的authorization_code模式
private SecurityScheme securitySchemeOauth2AuthorizationCode() {
return OAuth2Scheme.OAUTH2_AUTHORIZATION_CODE_FLOW_BUILDER
.name("oauth2的authorization_code模式")
.authorizationUrl("/oauth/authorize")
.tokenUrl("/oauth/token")
.scopes(scopes())
.build();
}
// oauth2下面的implicit模式
private SecurityScheme securitySchemeOauth2implicit() {
return OAuth2Scheme.OAUTH2_IMPLICIT_FLOW_BUILDER
.name("oauth2的implicit模式")
.authorizationUrl("/oauth/authorize")
.scopes(scopes())
.build();
}
// oauth2下面的ClientCredentials模式
private SecurityScheme securitySchemeOauth2ClientCredentials() {
return OAuth2Scheme.OAUTH2_CLIENT_CREDENTIALS_FLOW_BUILDER
.name("oauth2的clientCredentials模式")
.tokenUrl("/oauth/authorize")
.scopes(scopes())
.build();
}
// oauth2下面的password模式
private SecurityScheme securitySchemeOauth2Password() {
return OAuth2Scheme.OAUTH2_PASSWORD_FLOW_BUILDER
.name("oauth2的Password模式")
.tokenUrl("/oauth/token")
.scopes(scopes())
.build();
}
private List<AuthorizationScope> scopes() {
List<AuthorizationScope> list = new ArrayList<>();
list.add(new AuthorizationScope("read_scope", "Grants read access"));
list.add(new AuthorizationScope("write_scope", "Grants write access"));
list.add(new AuthorizationScope("admin_scope", "Grants read write and delete access"));
return list;
}
private SecurityContext securityContext() {
List<SecurityReference> list = new ArrayList<>();
// 这里的SecurityReference第一个参数值必须和SecurityScheme的name值一致
Arrays.stream(securitySchemeNames).forEach(name -> list.add(new SecurityReference(name, new AuthorizationScope[0])));
return SecurityContext.builder().operationSelector(operationContext -> {
System.out.println("operationContext" + operationContext);
// 除了get方法其他方法都要校验
// return !operationContext.httpMethod().name().equals("GET");
// 通过地址模糊匹配
AntPathMatcher pathMatcher = new AntPathMatcher();
String path = operationContext.requestMappingPattern();
return pathMatcher.match("/menu/**", path) || pathMatcher.match("/user/**", path);
}).securityReferences(list).build();
}
}