受權碼模式(authorization code)是功能最完整、流程最嚴密的受權模式。它的特色就是經過客戶端的後臺服務器,與"服務提供商"的認證服務器進行互動。git
它的步驟以下:github
(A)用戶訪問客戶端,後者將前者導向認證服務器。json
(B)用戶選擇是否給予客戶端受權。緩存
(C)假設用戶給予受權,認證服務器將用戶導向客戶端事先指定的"重定向URI"(redirection URI),同時附上一個受權碼。服務器
(D)客戶端收到受權碼,附上早先的"重定向URI",向認證服務器申請令牌。這一步是在客戶端的後臺的服務器上完成的,對用戶不可見。app
(E)認證服務器覈對了受權碼和重定向URI,確認無誤後,向客戶端發送訪問令牌(access token)和更新令牌(refresh token)。ide
下面是上面這些步驟所須要的參數。測試
A步驟中,客戶端申請認證的URI,包含如下參數:ui
下面是一個例子。url
GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz
&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1
Host: server.example.com
C步驟中,服務器迴應客戶端的URI,包含如下參數:
下面是一個例子。
HTTP/1.1 302 Found
Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA &state=xyz
D步驟中,客戶端向認證服務器申請令牌的HTTP請求,包含如下參數:
下面是一個例子。
POST /token HTTP/1.1
Host: server.example.com Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW Content-Type: application/x-www-form-urlencoded grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
E步驟中,認證服務器發送的HTTP回覆,包含如下參數:
下面是一個例子。
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache { "access_token":"2YotnFZFEjr1zCsicMWpAA", "token_type":"example", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", "example_parameter":"example_value" }
從上面代碼能夠看到,相關參數使用JSON格式發送(Content-Type: application/json)。此外,HTTP頭信息中明確指定不得緩存。
若是上面沒好理解,下面是我從《跟我學shiro》這本書裏看到的,可能比較容易理解
資源擁有者(resource owner):能受權訪問受保護資源的一個實體,能夠是一我的,那咱們稱之爲最終用
戶;如新浪微博用戶 zhangsan;
資源服務器(resource server):存儲受保護資源,客戶端經過 access token 請求資源,資源服務器響應受
保護資源給客戶端;存儲着用戶 zhangsan 的微博等信息。
受權服務器(authorization server):成功驗證資源擁有者並獲取受權以後,受權服務器頒發受權令牌(Acce
ss Token)給客戶端。
客戶端(client):如新浪微博客戶端 weico、微格等第三方應用,也能夠是它本身的官方應用;其自己不存儲資
源,而是資源擁有者受權經過後,使用它的受權(受權令牌)訪問受保護資源,而後客戶端把相應的數據展現出
來 / 提交到服務器。「客戶端」 術語不表明任何特定實現(如應用運行在一臺服務器、桌面、手機或其餘設
備)。
1. 客戶端從資源擁有者那請求受權。受權請求能夠直接發給資源擁有者,或間接的經過受權服務器這種中
介,後者更可取。
2. 客戶端收到一個受權許可,表明資源服務器提供的受權。(獲取受權碼)
3. 客戶端使用它本身的私有證書及受權許可到受權服務器驗證。
4. 若是驗證成功,則下發一個訪問令牌。(獲取access_token訪問令牌)
5. 客戶端使用訪問令牌向資源服務器請求受保護資源。
6. 資源服務器會驗證訪問令牌的有效性,若是成功則下發受保護資源。(獲取訪問的受保護資源)
oauth2.0服務端實現主要涉及參數配置以下:
受權碼設置(code)
第三方經過code進行獲取 access_token的時候須要用到,code的超時時間爲10分鐘,一個code只能成功換取一次access_token即失效。
受權做用域(scope)
做用域表明用戶受權給第三方的接口權限,第三方應用須要向服務端申請使用相應scope的權限後,通過用戶受權,獲取到相應access_token後方可對接口進行調用。
令牌有效期(access_token)
access_token是調用受權關係接口的調用憑證,因爲access_token有效期(目前爲2個小時)較短,當access_token超時後,能夠使用refresh_token進行刷新,access_token刷新結果有兩種: s
1. 若access_token已超時,那麼進行refresh_token會獲取一個新的access_token,新的超時時間;
2. 若access_token未超時,那麼進行refresh_token不會改變access_token,但超時時間會刷新,至關於續期access_token。
refresh_token擁有較長的有效期(30天),當refresh_token失效的後,須要用戶從新受權。
oauth2.0客戶端實現主要涉及傳參以下:
得到受權碼
http://localhost:8080/oauth2/authorize?client_id=fbed1d1b4b1449daa4bc49397cbe2350&response_type=code&redirect_uri=http://localhost:8080/oauth_callback
得到令牌(POST)
http://localhost:8080/oauth2/access_token?client_id=fbed1d1b4b1449daa4bc49397cbe2350&client_secret=fbed1d1b4b1449daa4bc49397cbe2350&grant_type=authorization_code&redirect_uri=http://localhost:8080/oauth_callback&code={code}
刷新令牌
client_id和client_secret是經過申請的,假如你要請求qq的oauth2.0服務,你得提早申請。若是是你本身的ouath服務,則須要在服務端對請求的client_id和client_secret驗證經過。
也能夠使用以下客戶端測試代碼,訪問 http://localhost:8080/client 測試
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
/*
* Created by Irving on 2014/11/24.
* OAuth2 客戶端實現
*/
@Controller
@RequestMapping(
"/client"
)
public
class
ClientController {
private
static
Logger logger = LoggerFactory.getLogger(ClientController.
class
);
/*
response_type:表示受權類型,必選項,此處的值固定爲"code"
client_id:表示客戶端的ID,必選項
redirect_uri:表示重定向URI,可選項
scope:表示申請的權限範圍,可選項
state:表示客戶端的當前狀態,能夠指定任意值,認證服務器會原封不動地返回這個值
*/
/**
* 得到受權碼
* @return
*/
@RequestMapping(method = RequestMethod.GET)
public
String client() {
try
{
OAuthClientRequest oauthResponse = OAuthClientRequest
.authorizationLocation(ConstantKey.OAUTH_CLIENT_AUTHORIZE)
.setResponseType(OAuth.OAUTH_CODE)
.setClientId(ConstantKey.OAUTH_CLIENT_ID)
.setRedirectURI(ConstantKey.OAUTH_CLIENT_CALLBACK)
.setScope(ConstantKey.OAUTH_CLIENT_SCOPE)
.buildQueryMessage();
return
"redirect:"
+oauthResponse.getLocationUri();
}
catch
(OAuthSystemException e) {
e.printStackTrace();
}
return
"redirect:/home"
;
}
/*
grant_type:表示使用的受權模式,必選項,此處的值固定爲"authorization_code"
code:表示上一步得到的受權碼,必選項。
redirect_uri:表示重定向URI,必選項,且必須與A步驟中的該參數值保持一致
client_secret:客戶端密鑰,必選項
client_id:表示客戶端ID,必選項
*/
/**
* 得到令牌
* @return oauth_callback?code=1234
*/
@RequestMapping(value =
"/oauth_callback"
,method = RequestMethod.GET)
public
String getToken(HttpServletRequest request,Model model) throws OAuthProblemException {
OAuthAuthzResponse oauthAuthzResponse =
null
;
try
{
oauthAuthzResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
String code = oauthAuthzResponse.getCode();
OAuthClientRequest oauthClientRequest = OAuthClientRequest
.tokenLocation(ConstantKey.OAUTH_CLIENT_ACCESS_TOKEN)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(ConstantKey.OAUTH_CLIENT_ID)
.setClientSecret(ConstantKey.OAUTH_CLIENT_SECRET)
.setRedirectURI(ConstantKey.OAUTH_CLIENT_CALLBACK)
.setCode(code)
.buildQueryMessage();
OAuthClient oAuthClient =
new
OAuthClient(
new
URLConnectionClient());
//Facebook is not fully compatible with OAuth 2.0 draft 10, access token response is
//application/x-www-form-urlencoded, not json encoded so we use dedicated response class for that
//Custom response classes are an easy way to deal with oauth providers that introduce modifications to
//OAuth 2.0 specification
//獲取access token
OAuthJSONAccessTokenResponse oAuthResponse = oAuthClient.accessToken(oauthClientRequest, OAuth.HttpMethod.POST);
String accessToken = oAuthResponse.getAccessToken();
String refreshToken= oAuthResponse.getRefreshToken();
Long expiresIn = oAuthResponse.getExpiresIn();
//得到資源服務
OAuthClientRequest bearerClientRequest =
new
OAuthBearerClientRequest(ConstantKey.OAUTH_CLIENT_GET_RESOURCE)
.setAccessToken(accessToken).buildQueryMessage();
OAuthResourceResponse resourceResponse = oAuthClient.resource(bearerClientRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.
class
);
String resBody = resourceResponse.getBody();
logger.info(
"accessToken: "
+accessToken +
" refreshToken: "
+refreshToken +
" expiresIn: "
+expiresIn +
" resBody: "
+resBody);
model.addAttribute(
"accessToken"
,
"accessToken: "
+accessToken +
" resBody: "
+resBody);
return
"oauth2/token"
;
}
catch
(OAuthSystemException ex) {
logger.error(
"getToken OAuthSystemException : "
+ ex.getMessage());
model.addAttribute(
"errorMsg"
, ex.getMessage());
return
"/oauth2/error"
;
}
}
}
|
項目結構以下:
AuthzController:獲取受權碼 (resource owner)
TokenController:得到令牌 (authorization server)
ResourceController:資源服務 (resource server)
ClientController:客戶端 (client)
前三個Controller相前於服務端 最後一個爲客戶端
基礎代碼放到github:https://github.com/peterowang/oauth2.0