返回介绍

文档

中间件

OAS 简介

实战指南

3.19 OAuth2

发布于 2022-12-06 22:06:14 字数 24070 浏览 0 评论 0 收藏 0

Knife4j提供的OAuth2认证功能相对于原生SwaggerUi来说使用起来更加方便,因此也归为增强属性一类。至少从交互上而言。

Knife4j自2.0.6版本开始添加对OAuth2的认证支持

目前支持的OAuth2模式包括:简化模式(implicit)、授权码模式(authorization_code)、密码模式(password)、客户端模式(client_credentials)

3.19.1 简化模式(implicit)

简化模式(implicit)在Knife4j中界面显示效果如下(点击左侧菜单Authorize查看):

简化模式(implicit)需要配置Knife4j提供的OAuth2的回调地址,回调页面位于 knife4j-spring-ui.jar

资源目录: webjars/oauth/oauth2.html

因此,需要在服务端配置该回调地址,Spring Security OAuth2示例代码如下:

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//简化模式(implicit)
clients.inMemory()
.withClient("app1").secret("123")
.authorizedGrantTypes("implicit")
.redirectUris(\"http://192.168.1.10:8080/webjars/oauth/oauth2.html")
.scopes("read","write","reads","writes");
}

界面效果如下:

使用者直接输入 clientId ,点击授权,此时进行调整授权界面,开发者授权即可

注意:当点击按钮Authorize授权后,如果授权成功,接下来点击其余的接口进行调试时,在请求头会存在参数 Authorization ,如何在未授权之前打开了接口,则需要在授权后关闭该接口的Tab,然后重新打开

创建Swagger的授权配置示例代码:

点击查看代码
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
//schema
List<GrantType> grantTypes=new ArrayList<>();
//简单模式implicit
ImplicitGrant implicitGrant=new ImplicitGrant(new LoginEndpoint("http://localhost:8999/oauth/authorize"),"access_token");
grantTypes.add(implicitGrant);

OAuth oAuth=new OAuthBuilder().name("oauth2")
.grantTypes(grantTypes).build();
//context
//scope方位
List<AuthorizationScope> scopes=new ArrayList<>();
scopes.add(new AuthorizationScope("read","read all resources"));
SecurityReference securityReference=new SecurityReference("oauth2",scopes.toArray(new AuthorizationScope[]{}));
SecurityContext securityContext=new SecurityContext(CollectionUtil.newArrayList(securityReference),PathSelectors.ant("/api/**"));
//schemas
List<SecurityScheme> securitySchemes=CollectionUtil.newArrayList(oAuth);
//securyContext
List<SecurityContext> securityContexts=CollectionUtil.newArrayList(securityContext);

String groupName="2.X版本";
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.host("https://www.baidu.com")
.apiInfo(apiInfo())
.groupName(groupName)
.select()
.apis(RequestHandlerSelectors.basePackage("com.swagger.bootstrap.ui.demo.new2"))
.paths(PathSelectors.any())
.build()
.securityContexts(securityContexts).securitySchemes(securitySchemes);
return docket;
}

3.19.2 授权码模式(authorization_code)

授权码模式(authorization_code)在Knife4j中界面显示效果如下(点击左侧菜单Authorize查看):

授权码模式(authorization_code)需要配置Knife4j提供的OAuth2的回调地址,回调页面位于 knife4j-spring-ui.jar

资源目录: webjars/oauth/oauth2.html

因此,需要在服务端配置该回调地址,Spring Security OAuth2示例代码如下:

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//授权码模式(authorization code)
clients.inMemory()
.withClient("app1").secret("123")
.authorizedGrantTypes("authorization_code")
.redirectUris(\"http://192.168.1.10:8080/webjars/oauth/oauth2.html")
.scopes("read","write","reads","writes");
}

界面效果如下:

使用者直接输入 clientIdclientSecret 后,点击授权,此时进行调整授权界面,开发者授权即可

注意:当点击按钮Authorize授权后,如果授权成功,接下来点击其余的接口进行调试时,在请求头会存在参数 Authorization ,如何在未授权之前打开了接口,则需要在授权后关闭该接口的Tab,然后重新打开

创建Swagger的授权配置示例代码:

点击查看代码
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
//schema
List<GrantType> grantTypes=new ArrayList<>();
//授权码模式AuthorizationCodeGrant
TokenRequestEndpoint tokenRequestEndpoint=new TokenRequestEndpoint("http://localhost:8999/oauth/authorize","app1","123");
TokenEndpoint tokenEndpoint=new TokenEndpoint("http://192.168.1.10:8080/oauth/token","access_token");
AuthorizationCodeGrant authorizationCodeGrant=new AuthorizationCodeGrant(tokenRequestEndpoint,tokenEndpoint);
grantTypes.add(authorizationCodeGrant);

OAuth oAuth=new OAuthBuilder().name("oauth2")
.grantTypes(grantTypes).build();
//context
//scope方位
List<AuthorizationScope> scopes=new ArrayList<>();
scopes.add(new AuthorizationScope("read","read all resources"));
SecurityReference securityReference=new SecurityReference("oauth2",scopes.toArray(new AuthorizationScope[]{}));
SecurityContext securityContext=new SecurityContext(CollectionUtil.newArrayList(securityReference),PathSelectors.ant("/api/**"));
//schemas
List<SecurityScheme> securitySchemes=CollectionUtil.newArrayList(oAuth);
//securyContext
List<SecurityContext> securityContexts=CollectionUtil.newArrayList(securityContext);

String groupName="2.X版本";
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.host("https://www.baidu.com")
.apiInfo(apiInfo())
.groupName(groupName)
.select()
.apis(RequestHandlerSelectors.basePackage("com.swagger.bootstrap.ui.demo.new2"))
.paths(PathSelectors.any())
.build()
.securityContexts(securityContexts).securitySchemes(securitySchemes);
return docket;
}

3.19.3 客户端模式(client_credentials)

客户端模式(client_credentials)在Knife4j中界面显示效果如下(点击左侧菜单Authorize查看):

界面效果如下:

使用者直接输入 clientIdclientSecret 后,点击授权即可

注意:当点击按钮Authorize授权后,如果授权成功,接下来点击其余的接口进行调试时,在请求头会存在参数 Authorization ,如何在未授权之前打开了接口,则需要在授权后关闭该接口的Tab,然后重新打开

创建Swagger的授权配置示例代码:

点击查看代码
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
//schema
List<GrantType> grantTypes=new ArrayList<>();
//客户端模式(client credentials)
String clientTokenUrl="http://192.168.1.10:8080/oauth/token";
ClientCredentialsGrant clientCredentialsGrant=new ClientCredentialsGrant(clientTokenUrl);
grantTypes.add(clientCredentialsGrant);


OAuth oAuth=new OAuthBuilder().name("oauth2")
.grantTypes(grantTypes).build();
//context
//scope方位
List<AuthorizationScope> scopes=new ArrayList<>();
scopes.add(new AuthorizationScope("read","read all resources"));
SecurityReference securityReference=new SecurityReference("oauth2",scopes.toArray(new AuthorizationScope[]{}));
SecurityContext securityContext=new SecurityContext(CollectionUtil.newArrayList(securityReference),PathSelectors.ant("/api/**"));
//schemas
List<SecurityScheme> securitySchemes=CollectionUtil.newArrayList(oAuth);
//securyContext
List<SecurityContext> securityContexts=CollectionUtil.newArrayList(securityContext);

String groupName="2.X版本";
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.host("https://www.baidu.com")
.apiInfo(apiInfo())
.groupName(groupName)
.select()
.apis(RequestHandlerSelectors.basePackage("com.swagger.bootstrap.ui.demo.new2"))
.paths(PathSelectors.any())
.build()
.securityContexts(securityContexts).securitySchemes(securitySchemes);
return docket;
}

3.19.4 密码模式(password)

密码模式(password)在Knife4j中界面显示效果如下(点击左侧菜单Authorize查看):

界面效果如下:

使用者直接输入 username , password , clientIdclientSecret 后,点击授权即可

注意:当点击按钮Authorize授权后,如果授权成功,接下来点击其余的接口进行调试时,在请求头会存在参数 Authorization ,如何在未授权之前打开了接口,则需要在授权后关闭该接口的Tab,然后重新打开

创建Swagger的授权配置示例代码:

点击查看代码
@Bean(value = "defaultApi2")
public Docket defaultApi2() {
//schema
List<GrantType> grantTypes=new ArrayList<>();
//密码模式
String passwordTokenUrl="http://192.168.1.10:8080/oauth/token";
ResourceOwnerPasswordCredentialsGrant resourceOwnerPasswordCredentialsGrant=new ResourceOwnerPasswordCredentialsGrant(passwordTokenUrl);
grantTypes.add(resourceOwnerPasswordCredentialsGrant);

OAuth oAuth=new OAuthBuilder().name("oauth2")
.grantTypes(grantTypes).build();
//context
//scope方位
List<AuthorizationScope> scopes=new ArrayList<>();
scopes.add(new AuthorizationScope("read","read all resources"));
SecurityReference securityReference=new SecurityReference("oauth2",scopes.toArray(new AuthorizationScope[]{}));
SecurityContext securityContext=new SecurityContext(CollectionUtil.newArrayList(securityReference),PathSelectors.ant("/api/**"));
//schemas
List<SecurityScheme> securitySchemes=CollectionUtil.newArrayList(oAuth);
//securyContext
List<SecurityContext> securityContexts=CollectionUtil.newArrayList(securityContext);

String groupName="2.X版本";
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.host("https://www.baidu.com")
.apiInfo(apiInfo())
.groupName(groupName)
.select()
.apis(RequestHandlerSelectors.basePackage("com.swagger.bootstrap.ui.demo.new2"))
.paths(PathSelectors.any())
.build()
.securityContexts(securityContexts).securitySchemes(securitySchemes);
return docket;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文