swagger oauth2 php,Swagger整合Oauth2

如果项目中使用了Oauth2.0,那么在每次请求接口的时候都需要在header上带上Authorization参数才可以正常访问,如下所示:

147f52983c039566ac622abc9f68369a.png

项目用了Swagger在线接口文档组件,那么如何结合Oauth2.0,让调用接口的时候自动带上认证参数呢?

以下就是Oauth2.0整合Swagger的步骤:

关键代码

@Configuration

@EnableSwagger2

public class SwaggerConfig {

private static final String VERSION = "1.0.0";

/**

* 创建API

*/

@Bean

public Docket createRestApi(){

return new Docket(DocumentationType.SWAGGER_2)

.apiInfo(apiInfo())

.select()

//指定接口包所在路径

.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))

.paths(PathSelectors.any())

.build()

//整合oauth2

.securitySchemes(Collections.singletonList(apiKey()))

.securityContexts(Collections.singletonList(securityContext()));

}

/**

* 添加摘要信息

*/

private ApiInfo apiInfo() {

return new ApiInfoBuilder()

.contact(new Contact("JAVA日知录","http://javadaily.cn","jianzh5@163.com"))

.title("account-server接口文档")

.description("account-server接口文档")

.termsOfServiceUrl("http://javadaily.cn")

.version(VERSION)

.build();

}

private ApiKey apiKey() {

return new ApiKey("Bearer", "Authorization", "header");

}

/**

* swagger2 认证的安全上下文

*/

private SecurityContext securityContext() {

return SecurityContext.builder()

.securityReferences(defaultAuth())

.forPaths(PathSelectors.any())

.build();

}

private List defaultAuth() {

AuthorizationScope authorizationScope = new AuthorizationScope("web", "access_token");

AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];

authorizationScopes[0] = authorizationScope;

return Collections.singletonList(new SecurityReference("Bearer",authorizationScopes));

}

}

使用步骤

使用postman调用认证中心接口获取access_token

http://localhost:8090/auth-service/oauth/token

{

"access_token": "36034ff7-7eea-4935-a3b7-5787d7a65827",

"token_type": "bearer",

"refresh_token": "4baea735-3c0d-4dfd-b826-91c6772a0962",

"expires_in": 36931,

"scope": "web"

}

访问Swagger接口页面,点击Authorize接口进行认证,在弹出框中输入Bearer 36034ff7-7eea-4935-a3b7-5787d7a65827并点击认证按钮。

1460000021932095

在Swagger中正常请求接口

d52410b22c3a56a5c586e42fa603b548.png

经过以上几步可以看到接口请求会默认带上认证参数,小伙伴们又可以愉快的玩耍了!

欢迎扫码关注微信公众号或 个人博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值