2021年1月19日 星期二

[Web] OAuth Authorization code flow筆記與取得google userinfo範例

 

Authorization Code是OAuth的其中一種授權方式,

可以讓client程式取得使用者(resource owner)外部的資源,需要使用者輸入帳密,

流程如下:

● 觸發驗證流程後,client程式將使用者的瀏覽器導向authorization server的驗證端點(authorize endpoint)。

● 此時網頁會顯示client程式想存取使用者在外部的哪些資源,等待使用者授權。

● authorization server依使用者回應與帳密決定是否授權。

  • 若使用者允許,則authorization server會依client程式註冊OAuth服務時填寫的redirection URI,將authorization code導回給client程式。
  • 若使用者不允許或無法成功授權,則將錯誤訊息導回client程式。

● client程式再帶authorization code、redirection URI等參數POST到authorization server的權杖端點(token endpoint)。

● authorization server確認參數無誤後,即回傳access token相關資訊,即可以此token跟resource server要資料。


以Flow chart描述流程如下:



來個實際操作吧,這邊使用Google OAuth來取得userinfo:

  • 先到google developer console的Credentials頁面,新增OAuth client ID,至少要給redirect URIs,儲存後就會拿到ClientID與Secret。
  • 組合取得Authorization code的url,紅色部份依實際狀況填入:

https://accounts.google.com/o/oauth2/v2/auth?

client_id=client id from google oauth setting&

redirect_uri=redirect_uri from google oauth setting&

response_type=code&

scope=profile&

access_type=offline&

state=up to you

  • GET呼叫取得Authorization code的url,google server會callback Authorization code,code通常是4%2F開頭,要注意有url encode,所以要轉為4/。
  • 接著POST呼叫要token,code就帶Authorization code,通常超過10分鐘會失效,如下圖,即可取得欲存取資源的token。


  • 最後拿token即可存取授權的資源:



參考資料:

https://tools.ietf.org/html/rfc6749

https://developers.google.com/identity/protocols/oauth2/web-server