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是一个关于授权的开放网络协议. 该协议在第三方应用与服务提供平台之间设置了一个授权层.第三方应用需要服务资源时,并不是直接使用用户帐 ...
随机推荐
- 文件上传的UI自动化
from pywinauto.application import Application import win32gui handle = win32gui.FindWindow("#32 ...
- node.js 调试问题
最近打算在项目过程中使用node.js辅助解决一些问题,需要用到node.js的调试技术. 通常而言,大家都会提到debugger或者node-inspector方法. debugger方法谁用谁知道 ...
- java 遇到的问题
1.list.sort(new Comparator<String>() { @override public int compare(String o1, String o2) { re ...
- Java 7 使用TWR(Try-with-resources)完成文件copy
try-with-resources语句是声明了一个或多个资源的try语句块.在java中资源作为一个对象,在程序完成后必须关闭.try-with-resources语句确保每个资源在语句结束时关闭. ...
- 万能的一句话 json
String str1 = new JavaScriptSerializer().Serialize(meetapply1);//meetapply1==object T
- Spring事务传递
2018-09-25 @Transactional(propagation=Propagation.NEVER) public void update(){ Session s = sessionFa ...
- springboot项目新功能开发
在原有的springboot项目上,复制了一个,然后将其中的src下的所有java文件都删除,gradle下把中间件都删除,直流springframework的,重新启动,发现 错误Failed to ...
- Java多线程系列4 线程交互(wait和notify方法)
wait()/ notify()/ notifyAll() 任何Object对象都可以作为这三个方法的主调,但是不推荐线程对象调用这些方法. 1使用wait().notify()和notifyAll( ...
- 第一次spring会议
1.今天查询了很多案例,找到了符合我们要求的案例,并进行了尝试. 2.昨天拍摄了宣传视频. 3.明天准备用C#限定格式输出TXT文件.
- 关于java poi itext生成pdf文件的例子以及方法
最近正在做导出pdf文件的功能,所以查了了一些相关资料,发现不是很完善,这里做一些小小的感想,欢迎各位“猿”童鞋批评指正. poi+itext,所需要的jar包有itext-2.1.7.jar,poi ...