shiro中OAuth2 集成


 

OAuth 角色


資源擁有者(resource owner

  能授權訪問受保護資源的一個實體,可以是一個人,那我們稱之為最終用戶;如新浪微博用戶 zhangsan

資源服務器(resource server

  存儲受保護資源,客戶端通過 access token 請求資源,資源服務器響應受保護資源給客戶端;存儲着用戶 zhangsan 的微博等信息。

授權服務器(authorization server

  成功驗證資源擁有者並獲取授權之后,授權服務器頒發授權令牌(Access Token)給客戶端。

客戶端(client

  如新浪微博客戶端 weico、微格等第三方應用,也可以是它自己的官方應用;其本身不存儲資源,而是資源擁有者授權通過后,使用它的授權(授權令牌)訪問受保護資源,然后客戶端把相應的數據展示出來/提交到服務器。“客戶端”術語不代表任何特定實現(如應用運行在一台服務器、桌面、手機或其他設備)。 

 

1、客戶端從資源擁有者那請求授權。授權請求可以直接發給資源擁有者,或間接的通過授權服務器這種中介,后者更可取

2、客戶端收到一個授權許可,代表資源服務器提供的授權。

3、客戶端使用它自己的私有證書及授權許可到授權服務器驗證。

4、如果驗證成功,則下發一個訪問令牌。

5、客戶端使用訪問令牌向資源服務器請求受保護資源。

6、資源服務器會驗證訪問令牌的有效性,如果成功則下發受保護資源。

 

要實現OAuth服務端,就得先理解客戶端的調用流程,服務提供商實現可能也有些區別,實現OAuth服務端的方式很多,具體可能看http://oauth.net/code/

各語言的實現有(我使用了Apache Oltu):

實現主要涉及參數配置如下: 
授權碼設置(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刷新結果有兩種: 
    1. 若access_token已超時,那么進行refresh_token會獲取一個新的access_token,新的超時時間; 
    2. 若access_token未超時,那么進行refresh_token不會改變access_token,但超時時間會刷新,相當於續期access_token。 
refresh_token擁有較長的有效期(30天),當refresh_token失效的后,需要用戶重新授權。

項目介紹

項目結構如下: 
AuthzController:獲取授權碼 
TokenController:獲得令牌 
ResourceController:資源服務 
ClientController:客戶端

基礎代碼放到github:https://github.com/zhouyongtao/homeinns-web

image

確保項目8080端口運行,可以手動調試

獲得授權碼 
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}

客戶端

也可以使用如下客戶端測試代碼,訪問 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
<font face= "Consolas" > /**
  * 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_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" ;
         }
     }
}
</font>

Refer: 
https://cwiki.apache.org/confluence/display/OLTU/Index 
https://open.weixin.qq.com/cgi-bin/readtemplate?t=resource/app_wx_login_tmpl&lang=zh_CN#faq

 

http://jinnianshilongnian.iteye.com/blog/2038646

http://blog.csdn.net/u014386474/article/details/51602264

http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html

http://www.cnblogs.com/nidakun/p/3195023.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM