- 在授权码模式下,允许为空。
可能有部分胖友是 Windows 电脑,可以参考 《windows(64位)下使用 curl 命令》 来安装一个 curl 命令。
当然,如果胖友使用 Postman ,可以参看如下两图:
- 图 1
- 图 2
⑥ 调用资源服务器的 API
curl -X GET http://localhost:8080/api/example/hello -H “authorization: Bearer e60e41f2-2ad0-4c79-97d5-49af38e5c2e8”
- authorization: Bearer e60e41f2-2ad0-4c79-97d5-49af38e5c2e8 处,填写指定的访问令牌类型和访问令牌。例如此处分别为,“Bearer”、“e60e41f2-2ad0-4c79-97d5-49af38e5c2e8” 。
如果胖友使用 Postman ,可以参看如下图:
- 图
4.2 密码模式
Maven 项目结构如下:
Maven 项目结构
对应 GitHub 地址:
https://github.com/YunaiV/SpringBoot-Labs/tree/f8d701cbd9b2a4f2cee3a7f2186148bcdf859895/lab-02/resource-owner-password-credentials-server
① 配置授权服务器
// 授权服务器配置
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {
// 用户认证
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(“clientapp”).secret(“112233”) // Client 账号、密码。
.authorizedGrantTypes(“password”) // 密码模式
.scopes(“read_userinfo”, “read_contacts”) // 可授权的 Scope
// .and().withClient() // 可以继续配置新的 Client
;
}
}
-
配置 Client 的方式,和【授权码模式】基本一致。差别在于:
-
无需配置 `redirectUris` 属性,因为不需要回调地址。
-
配置授权模式为【密码模式】。
-
另外,需要引入 AuthenticationManager 来支持【密码模式】,否则会报 “Resolved [error=“unsupported_grant_type”, error_description=“Unsupported grant type: password”]” 异常。
② 配置登陆账号
和【授权码模式】一致。
③ 启动项目
和【授权码模式】一致。
④ 获取访问令牌
curl -X POST --user clientapp:112233 http://localhost:8080/oauth/token -H “accept: application/json” -H “content-type: application/x-www-form-urlencoded” -d “grant_type=password&username=yunai&password=1024&scope=read_userinfo”
-
和【授权码模式】差异比较大。
-
直接请求 oauth/token 接口,获得访问令牌。
-
请求参数带上了 username 和 password ,就用户的登陆账号和密码。
-
请求参数 grant_type 为 password ,表示【密码模式】。
返回结果示例如下:
{
“access_token”: “68de6eb9-5672-4e47-a3e6-110404285ba9”,
“token_type”: “bearer”,
“expires_in”: 43199,
“scope”: “read_userinfo”
}
- 和【授权码模式】一致。
⑤ 调用资源服务器的 API
和【授权码模式】一致。
4.3 简化模式
Maven 项目结构如下:
Maven 项目结构
对应 GitHub 地址:
https://github.com/YunaiV/SpringBoot-Labs/tree/f8d701cbd9b2a4f2cee3a7f2186148bcdf859895/lab