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. 在IDEA中使用MyBatis Generator自动生成代码

    转载自 https://blog.csdn.net/hua_faded/article/details/78900780 一.配置Maven pom.xml 文件 在pom.xml增加以下插件:   ...

  2. stark组件开发之添加按钮显示和URL

    添加: 需求: 根据用户的权限, 决定是否,有添加按钮.  通过配置进行定制,预留钩子进行权限的判断. class StartHandler(object): .................... ...

  3. python基础之Day12

    一.闭包函数 什么是闭包函数? 闭:函数是一个内部函数 包:指的是该函数包含对外部作用域(非全局作用域)名字的引用. 给函数传值的方式有两种: 1.使用参数直接给函数传值 2.包给函数 1 2 3 4 ...

  4. Spring MVC 上传和下载文件

    上传文件 Commons FileUpload 元件 Servlet 3.0 本地文件上传特性 HTML 5 下载文件

  5. maven打包自定义jar到maven仓库

    mvn install:install-file -Dfile=F:/Sdk4j.jar -DgroupId=com.sdk4j -DartifactId=sdk4j -Dversion=1.0 -D ...

  6. [uboot] (第四章)uboot流程——uboot编译流程

    http://blog.csdn.net/ooonebook/article/details/53000893 以下例子都以project X项目tiny210(s5pv210平台,armv7架构)为 ...

  7. 别人的Linux私房菜(8)Linux磁盘与文件系统管理

    虚拟机的磁盘通常为:/dev/vd[a-p] LVM和软件磁盘阵列 software RAID可以将一个分区格式化为多个文件系统或者多个分区格式化为一个文件系统. 索引式文件系统中:如ext2.ext ...

  8. MUI 里js动态添加数字输入框后,增加、减少按钮无效

    numbox 的自动初化是在 mui.ready 时完成的mui 页面默认会自动初始化页面中的所有数字输入框,动态构造的 DOM 需要进行手动初始化.比如:您动态创建了一个 ID 为 abc 的数字输 ...

  9. LOJ-10103(求删去割点后最多的连通分量)

    题目链接:传送门 思路: (1)这道题的图可能不连通,所以需要多次Tarjan: (2)设置cut[i]=x数组表示第i个节点被删除后右多少个子图(这个只是在一个图中),如果是根节点就要-1,因为根节 ...

  10. python基本数据类型之字符串(二)

    python基本数据类型之字符串(二) 替换方法 python中字符串的替换方法主要有:center.rjust\ljust.expandtabs.format\format_map(格式化).str ...