Spring Boot 集成 Swagger2 与配置 OAuth2.0 授权
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 授权的更多相关文章
- Spring boot集成Swagger2,并配置多个扫描路径,添加swagger-ui-layer
Spring boot集成Swagger,并配置多个扫描路径 1:认识Swagger Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目 ...
- Spring boot集成swagger2
一.Swagger2是什么? Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件. Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格 ...
- 解决Spring Boot集成Shiro,配置类使用Autowired无法注入Bean问题
如题,最近使用spring boot集成shiro,在shiroFilter要使用数据库动态给URL赋权限的时候,发现 @Autowired 注入的bean都是null,无法注入mapper.搜了半天 ...
- Spring Boot 集成Swagger2生成RESTful API文档
Swagger2可以在写代码的同时生成对应的RESTful API文档,方便开发人员参考,另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API. 使用Spring Boot可 ...
- Spring Boot 集成 Swagger2 教程
上篇讲过 Spring Boot RESTful api ,这篇简单介绍下 SwaggerUI 在 Spring Boot 中的应用. Swagger 是一个规范和完整的框架,用于生成.描述.调用和可 ...
- JMeter配置Oauth2.0授权接口访问
本文主要介绍如何使用JMeter配置客户端凭证(client credentials)模式下的请求 OAuth2.0介绍 OAuth 2.0 是一种授权机制,主要用来颁发令牌(token) 客户端凭证 ...
- spring boot 集成swagger2
1 在pom.xml中加入Swagger2的依赖 <dependency> <groupId>io.springfox</groupId> <artifac ...
- Spring Boot之Swagger2集成
一.Swagger2简单介绍 Swagger2,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档.它既可以减少我们创建文档的工作量,同时 ...
- Spring Security实现OAuth2.0授权服务 - 基础版
一.OAuth2.0协议 1.OAuth2.0概述 OAuth2.0是一个关于授权的开放网络协议. 该协议在第三方应用与服务提供平台之间设置了一个授权层.第三方应用需要服务资源时,并不是直接使用用户帐 ...
随机推荐
- python动态模块导入
首先创建一个模块目录lib,然后在目录内创建一个模块为:aa.py 官方推荐: import importlib aa = importlib.import_module('lib.aa') c = ...
- 35 【kubernetes】configMap
kubernetes可以驱动容器的运行,并且把容器的运行放置在kubernetes定义的体系结构中pods这一级. 但是容器运行通常会需要某些参数,比如环境变量或者硬件使用情况. 为了解决对每个con ...
- 手动添加jar包到本地maven仓库
我们都知道使用maven管理jar包的时候,我们需要到远程仓库下载相关的jar包到本地仓库,但是如果远程仓库没有这个jar包呢?这时候我们就需要手动将jar包添加到本地仓库. 起因是我想用百度的富文本 ...
- 129. Sum Root to Leaf Numbers pathsum路径求和
[抄题]: Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a ...
- py2和py3的区别总结
1.编码 python2默认编码方式ASCII码(不能识别中文,要在文件头部加上 #-*- encoding:utf-8 -*- 指定编码方式) python3默认编码方式unicode(可识别中 ...
- android开发环境配置以及测试所遇到的的问题
今天我没有继续进行,整理了一线之前犯下的错误.在一开始的android的环境配置的时候,按照网上的教程,我还是走了许多弯道,其中遇到了不少的问题,但是现在都一一解决了. 配置时安装东西少 在配置的时候 ...
- VS“新建网站”与“新建Asp.Net Web 应用程序”的区别
WebApplication(新建Asp.Net Web 应用程序)编程模型的优点:针对大型网站 1.编译速度网站编译速度快,使用了增量编译模式,仅仅只有文件被修改后,这部分才会被增量编译进去. 2. ...
- Hadoop 系列文章(二) Hadoop配置部署启动HDFS及本地模式运行MapReduce
接着上一篇文章,继续我们 hadoop 的入门案例. 1. 修改 core-site.xml 文件 [bamboo@hadoop-senior hadoop-2.5.0]$ vim etc/hadoo ...
- [UWP]在UWP平台中使用Lottie动画
最近QQ影音久违的更新了,因为记得QQ影音之前体验还算不错(FFmepg的事另说),我也第一时间去官网下载体验了一下,结果发现一些有趣的事情. 是的,你没看错,QQ影音主界面上这个动画效果是使用Lot ...
- 背水一战 Windows 10 (92) - 文件系统: 读写“最近访问列表”和“未来访问列表”, 管理以及使用索引
[源码下载] 背水一战 Windows 10 (92) - 文件系统: 读写“最近访问列表”和“未来访问列表”, 管理以及使用索引 作者:webabcd 介绍背水一战 Windows 10 之 文件系 ...