Spring Boot 集成 Swagger2 很简单,由于接口采用了OAuth2.0 & JWT 协议做了安全验证,使用过程中也遇到了很多小的问题,多次尝试下述配置可以正常使用。

Maven

        <!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>2.8.0</version>
</dependency>
Swagger2Configuration
@Configuration
@EnableSwagger2
public class Swagger2Configuration { // @Value("${config.oauth2.accessTokenUri}")
private String accessTokenUri ="http://localhost:8080/oauth/token"; private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API 接口服务")
.description("API 接口服务")
.termsOfServiceUrl("http://www.cnblogs.com/irving")
.version("v1")
.license("Apache License Version 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0")
.contact(new Contact("irving","http://www.cnblogs.com/irving","zhouyongtao@outlook.com"))
.build();
} @Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.holiday.sunweb.controller"))
//.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build()
.securityContexts(Collections.singletonList(securityContext()))
.securitySchemes(Arrays.asList(securitySchema(), apiKey(), apiCookieKey()));
// .globalOperationParameters(
// newArrayList(new ParameterBuilder()
// .name("access_token")
// .description("AccessToken")
// .modelRef(new ModelRef("string"))
// .parameterType("query")
// .required(true)
// .build()));
} @Bean
public SecurityScheme apiKey() {
return new ApiKey(HttpHeaders.AUTHORIZATION, "apiKey", "header");
} @Bean
public SecurityScheme apiCookieKey() {
return new ApiKey(HttpHeaders.COOKIE, "apiKey", "cookie");
} private OAuth securitySchema() { List<AuthorizationScope> authorizationScopeList = newArrayList();
authorizationScopeList.add(new AuthorizationScope("read", "read all"));
authorizationScopeList.add(new AuthorizationScope("write", "access all"));
List<GrantType> grantTypes = newArrayList();
GrantType passwordCredentialsGrant = new ResourceOwnerPasswordCredentialsGrant(accessTokenUri);
grantTypes.add(passwordCredentialsGrant); return new OAuth("oauth2", authorizationScopeList, grantTypes);
} private SecurityContext securityContext() {
return SecurityContext.builder().securityReferences(defaultAuth())
.build();
} private List<SecurityReference> defaultAuth() { final AuthorizationScope[] authorizationScopes = new AuthorizationScope[3];
authorizationScopes[0] = new AuthorizationScope("read", "read all");
authorizationScopes[1] = new AuthorizationScope("trust", "trust all");
authorizationScopes[2] = new AuthorizationScope("write", "write all"); return Collections.singletonList(new SecurityReference("oauth2", authorizationScopes));
} // @Bean
// public SecurityConfiguration security() {
// return new SecurityConfiguration
// ("client", "secret", "", "", "Bearer access token", ApiKeyVehicle.HEADER, HttpHeaders.AUTHORIZATION,"");
// } @Bean
SecurityConfiguration security() {
return SecurityConfigurationBuilder.builder()
.clientId("client_test")
.clientSecret("secret_test")
.realm("test-app-realm")
.appName("test-app")
.scopeSeparator(",")
.additionalQueryStringParams(null)
.useBasicAuthenticationWithAccessCodeGrant(false)
.build();
} @Bean
UiConfiguration uiConfig() {
return UiConfigurationBuilder.builder()
.deepLinking(true)
.displayOperationId(false)
.defaultModelsExpandDepth(1)
.defaultModelExpandDepth(1)
.defaultModelRendering(ModelRendering.EXAMPLE)
.displayRequestDuration(false)
.docExpansion(DocExpansion.NONE)
.filter(false)
.maxDisplayedTags(null)
.operationsSorter(OperationsSorter.ALPHA)
.showExtensions(false)
.tagsSorter(TagsSorter.ALPHA)
.validatorUrl(null)
.build();
}
}
UserController
@Api(value = "用户接口服务", description = "用户接口服务")
@RestController
@RequestMapping("/api/v1/users")
public class UserController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private UserRepository userRepository; @ApiOperation(value = "查询通过 OAuth2.0 授权后获取的用户信息", notes = "通过 OAuth2.0 授权后获取的用户信息")
@GetMapping("/principal")
public Principal principal(Principal principal)
{
return principal;
} @ApiOperation(value = "根据用户名查询用户信息", notes = "根据用户名查询用户信息")
@GetMapping("/{username}")
public BaseMsg GetUserInfoByUserName(@PathVariable String username) {
return BaseMsgResponse.success(userRepository.findOneByusername(username));
} @ApiOperation(value = "根据ID删除一个用户", notes = "根据ID删除一个用户")
@DeleteMapping("/{id}")
public BaseMsg getInfoByName(@PathVariable Integer id) {
userRepository.deleteById(id);
return BaseMsgResponse.success();
}
}

最后访问 http://localhost:8080/swagger-ui.html#/

配置 Resource Owner Password Credentials 模式的 Client

Test

问题:

swagger-2.9.1 /csrf is 404 问题

A:这个问题在 2.9.x 版本中有(https://github.com/springfox/springfox/issues/2603) ,暂时还没有找到好的解决方案,回退到 2.8.0 版本。

配置 ApiKey 后 HTTP 头 Authorization: Bearer {THE TOKEN} 不生效问题

A:2.7.x 版本没有问题(https://github.com/springfox/springfox/issues/1812)

@Bean
public SecurityScheme apiKey() {
return new ApiKey(HttpHeaders.AUTHORIZATION, "apiKey", "header");
}

后面使用了 OAuth2.0 协议在 2.8.0 版本中无问题。

REFER:
https://springfox.github.io/springfox/docs/current/
https://github.com/springfox/springfox
https://github.com/rrohitramsen/spring-boot-oauth2-jwt-swagger-ui

Spring Boot 集成 Swagger2 与配置 OAuth2.0 授权的更多相关文章

  1. Spring boot集成Swagger2,并配置多个扫描路径,添加swagger-ui-layer

    Spring boot集成Swagger,并配置多个扫描路径 1:认识Swagger Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目 ...

  2. Spring boot集成swagger2

    一.Swagger2是什么? Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件. Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格 ...

  3. 解决Spring Boot集成Shiro,配置类使用Autowired无法注入Bean问题

    如题,最近使用spring boot集成shiro,在shiroFilter要使用数据库动态给URL赋权限的时候,发现 @Autowired 注入的bean都是null,无法注入mapper.搜了半天 ...

  4. Spring Boot 集成Swagger2生成RESTful API文档

    Swagger2可以在写代码的同时生成对应的RESTful API文档,方便开发人员参考,另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API. 使用Spring Boot可 ...

  5. Spring Boot 集成 Swagger2 教程

    上篇讲过 Spring Boot RESTful api ,这篇简单介绍下 SwaggerUI 在 Spring Boot 中的应用. Swagger 是一个规范和完整的框架,用于生成.描述.调用和可 ...

  6. JMeter配置Oauth2.0授权接口访问

    本文主要介绍如何使用JMeter配置客户端凭证(client credentials)模式下的请求 OAuth2.0介绍 OAuth 2.0 是一种授权机制,主要用来颁发令牌(token) 客户端凭证 ...

  7. spring boot 集成swagger2

    1  在pom.xml中加入Swagger2的依赖 <dependency> <groupId>io.springfox</groupId> <artifac ...

  8. Spring Boot之Swagger2集成

    一.Swagger2简单介绍 Swagger2,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档.它既可以减少我们创建文档的工作量,同时 ...

  9. Spring Security实现OAuth2.0授权服务 - 基础版

    一.OAuth2.0协议 1.OAuth2.0概述 OAuth2.0是一个关于授权的开放网络协议. 该协议在第三方应用与服务提供平台之间设置了一个授权层.第三方应用需要服务资源时,并不是直接使用用户帐 ...

随机推荐

  1. 360. Sort Transformed Array二元一次方程返回大数序列

    [抄题]: Given a sorted array of integers nums and integer values a, b and c. Apply a quadratic functio ...

  2. webapi postman 415 错误

    https://blog.csdn.net/Intangible_moon/article/details/80183121 猜测:如果后台接口使用的是[fromBody]标签的话,需要使用raw方式

  3. etcd-v2第四集

    coreos把etcd的image放到自家的quay.io,而不是hub.docker,或许是竞争关系,但国内下载quay.io容器极难,反正shadowsocks是下载不了. 幸好有热心爱好者搬运到 ...

  4. 1,postman的安装

    1,下载postman 2,安装,下载和自己系统相对应的版本 本人下载的是window版本的,直接一步步安装就行 打开后进入下边的界面 建议使用native版本的postman,chrome插件的po ...

  5. rsyslog和logrotate

    简介 rsyslog 是一个 syslogd 的多线程增强版. 现在Fedora和Ubuntu, rhel6默认的日志系统都是rsyslog了 rsyslog负责写入日志, logrotate负责备份 ...

  6. windows Sql server performance monitor

    对于sql server 性能的监控主要从2个方面: 1. sql server自带的监控 Management->SQL Server Logs->Activity Monitor 在这 ...

  7. Pivot For和UNPivot For

    一.使用PIVOT和UNPIVOT命令的SQL Server版本要求 1.数据库的最低版本要求为SQL Server 2005 或更高. 2.必须将数据库的兼容级别设置为90 或更高. 3.查看我的数 ...

  8. tensorflow学习之(三)Varible 变量的使用

    #Varible 变量的使用 使用变量进行自加 import tensorflow as tf state = tf.Variable(0,name='counter') #定义一个变量,赋值为0,且 ...

  9. s33 cobbler自动化安装系统

    1. Cobbler介绍 参考链接:http://blog.oldboyedu.com/autoinstall-cobbler/ Cobbler是一个Linux服务器安装的服务,可以通过网络启动(PX ...

  10. Chapter6 胞内信号网络

    一.一条从细胞表面到细胞核的通路 二.Ras蛋白处于复杂信号级联的中心位置 胞外信号→酪氨酸激酶受体→Shc→Grb→Sos→Ras 三.酪氨酸的磷酸化控制着许多胞内信号蛋白的定位与活动 Src蛋白的 ...