这篇文章只是让你了解OAuth2client_credentials 和refresh_token 授予类型的基本概念和例子。除此之外,你还应该知道OAuth 2.0 Token Introspection端点,它提供了关于令牌的元信息:
-
访问令牌过期,TTL由你决定,例如1小时。
-
刷新令牌会过期,但TTL通常比访问令牌的TTL长很多,例如1周。
-
访问令牌用于消费API。
-
刷新令牌用于获得一个新的访问令牌,是响应中的一个可选属性。
更多信息请阅读《OAuth 2.0授权框架》
客户端注册流程
请求
curl -X POST https://api.hello.com/v1/{clients|register}
-H 'Content-Type: application/json'
-d '{"username":"client-email@domain.com","password":"client-password"}'
响应
201 Created
{
"client_id": "ID",
"client_key": "KEY",
"client_secret": "SECRET"
}
客户凭证流程
请阅读相关信息。客户端凭证授予/访问令牌请求/访问令牌响应。下面的S0VZOlNFQ1JFVA== 是base64_encode的KEY:SECRET 组合。
请求
curl -X POST https://api.hello.com/v1/oauth/token
-H 'Authorization: Basic S0VZOlNFQ1JFVA=='
-H 'content-type: application/x-www-form-urlencoded'
-d 'grant_type=client_credentials'
响应
200 OK
Cache-Control: no-store
Pragma: no-cache
{
"access_token": "ACCESS_TOKEN",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "REFRESH_TOKEN"
}
刷新令牌流程
请求
curl -X POST https://api.hello.com/v1/oauth/token
-H 'Authorization: Basic S0VZOlNFQ1JFVA=='
-H 'content-type: application/x-www-form-urlencoded'
-d 'grant_type=refresh_token&refresh_token=REFRESH_TOKEN'
响应
200 OK
Cache-Control: no-store
Pragma: no-cache
{
"access_token": "NEW_ACCESS_TOKEN",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "NEW_REFRESH_TOKEN"
}
消耗OAuth2认证的API
请求
curl -X GET https://api.hello.com/v1/resource
-H 'Authorization: Bearer ACCESS_TOKEN'