> For the complete documentation index, see [llms.txt](https://jen-hsuan-hsieh.gitbook.io/asp-net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jen-hsuan-hsieh.gitbook.io/asp-net/chapter3rest-api-design-development-and-management/34rest-api-security/345api-authorization-using-oauth20.md).

# 3.4.5.API Authorization using OAuth2.0

* OAuth2.0 has become the defactor standard for building authorization (授權) for REST APIs as Facebook, Linkedin and Spotify
* Customer Information
  * 第三方服務直接透過API取得客戶的資料是不合理的, 因為沒有取得客戶的授權

    ![](https://github.com/jenhsuan/asp-net/tree/4be758d868ba14011a3e816f30e65a6ee7ad7252/assets/未命名1133.jpg)
* Authorization
  * 合理的做法應該是: 第三方服務先取得客戶授權, 再透過API取得客戶資料

    ![](https://github.com/jenhsuan/asp-net/tree/4be758d868ba14011a3e816f30e65a6ee7ad7252/assets/未命名1144.jpg)
* [OAuth2.0](https://tools.ietf.org/html/rfc6749)
  * Flexible Authorization **framework**
    * Uses different types of tokens
    * **Described 5 methods (grants) for acquiring access tokens**
      * 1.Authorization scope grant
      * 2.Client credentials grant
      * 3.Implicit grant
      * 4.Refresh token grant
      * 5.Resource owner credentials grant

        ![](https://github.com/jenhsuan/asp-net/tree/4be758d868ba14011a3e816f30e65a6ee7ad7252/assets/未命名1167.jpg)
    * End user in control of their data (scope)
    * Application/ Client needs a API key & secret
* OAuth2.0 Tokens
  * 1.Authorization Token
    * Proof of authorization
    * Issued after user logs in and authorize
  * 2.Access Token
    * Credential for accessing the protected resource
      * Provider may define multiple types: 不同token會對應到不同scope
      * e.g., [facebook](https://developers.facebook.com/docs/facebook-login/access-tokens)
    * Expiry set by issuer
  * 3.Refresh Token
    * May be used for extending access token validity
* 流程 (簡易)
  * 有三個主要腳色
    * 1.User
    * 2.Application/client
    * 3.Authorization server/ resource server (API provider)

      ![](https://github.com/jenhsuan/asp-net/tree/4be758d868ba14011a3e816f30e65a6ee7ad7252/assets/未命名1145.jpg)
* OAuth2.0 Design Decisions
  * Scopes of the user data (API)
  * Type of OAuth grants to be supported
    * Authorization || Implicit grant         private data
    * Client credentials                      public data
    * For trusted clients would you use "Resource owner credentials grant"?
  * Implementing the OAuth
    * Build
    * API Management Platform
* 何時不採用OAuth
  * 以下兩種場景
    * API僅供消遣使用, 如果某個惡意軟件竊取了證書, 也不會造成任何破壞&#x20;
    * API的用戶都編寫屬於自己的應用程式
