记录一次spring发布的oauth2服务器demo学习——第三步,获取资源其他授权方式

获取资源服务器资源

官方给出了两个client的案例,一个是authorization_code模式,一个是client_credentials模式

@GetMapping(value = "/authorize", params = "grant_type=authorization_code")
public String authorizationCodeGrant(Model model,
@RegisteredOAuth2AuthorizedClient("messaging-client-authorization-code")
OAuth2AuthorizedClient authorizedClient) {
String[] messages = this.webClient
.get()
.uri(this.messagesBaseUri)
.attributes(oauth2AuthorizedClient(authorizedClient))
.retrieve()
.bodyToMono(String[].class)
.block();
model.addAttribute("messages", messages);
return "index";
}
@GetMapping(value = "/authorize", params = "grant_type=client_credentials")
public String clientCredentialsGrant(Model model) {
String[] messages = this.webClient
.get()
.uri(this.messagesBaseUri)
.attributes(clientRegistrationId("messaging-client-client-credentials"))
.retrieve()
.bodyToMono(String[].class)
.block();
model.addAttribute("messages", messages);
return "index";
}

本质上都是给请求加了一个请求头 Authorization,传递授权服务器给的 Bearer token,这点我们可以在resource服务器看到
image
image

客户端凭证授权

该方式一般只在后台服务器之间进行交互,而且该交互所得的token没有暴露的必要,故官方为明确给出演示方法,但是我们可以通过上面的案例,确定该登录方式本质也是在请求头加上一个 Authorization,值为:"Basic " + Base64.getUrlEncoder().encodeToString("client-id:secret".getBytes(StandardCharsets.UTF_8));。加上表单传参:

key value remark
grant_type client_credentials 客户端凭证授权
scope message.read message.write 设置授权范围
image
image
此处说明下,postman有相应认证相对友好的配置界面,如下,我们不需要自己去对client凭证进行base64编码,设置请求头。
如果不是非常熟悉协议或者快速切账号调试的话不建议这样设置,毕竟http协议本身所需要进行的配置简单明了,反而在这里隐藏了数据转换的话,让我们更迷糊
image
image

token刷新授权

和客户端凭证授权一样设置请求头,Authorization"Basic " + Base64.getUrlEncoder().encodeToString("client-id:secret".getBytes(StandardCharsets.UTF_8));

key value remark
grant_type refresh_token token刷新授权
refresh_token afojMKL-ZS3hbSNBGaRXGAsl2ixEund0iCOUSqbSUdbLJT6MkYzQ2EqS2lyQMyosiNmMMl4aGfmsI7EzrUpu9QqYnB4RXgsASaGG4QjQo2U_Pd7f1VsqW42zmaL3LY9I 用于token刷新验证的token
posted @   临渊不羡渔  阅读(321)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示