记录一次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服务器看到


客户端凭证授权
该方式一般只在后台服务器之间进行交互,而且该交互所得的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 | 设置授权范围 |
![]() |
||
![]() |
||
| 此处说明下,postman有相应认证相对友好的配置界面,如下,我们不需要自己去对client凭证进行base64编码,设置请求头。 | ||
| 如果不是非常熟悉协议或者快速切账号调试的话不建议这样设置,毕竟http协议本身所需要进行的配置简单明了,反而在这里隐藏了数据转换的话,让我们更迷糊 | ||
![]() |
||
![]() |
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 |
![]() |
||
![]() |







浙公网安备 33010602011771号