葉佳臻
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: Other --- # OAuth 開放授權(Open Authorization)是一個開放標準,**授權一個特定的應用在特定的時段內存取特定的資源**,而無需將用戶名稱和密碼提供給第三方應用。 > The OAuth protocol enables websites or applications (Consumers) to access Protected Resources from a web service (Service Provider) via an API, without requiring Users to disclose their Service Provider credentials to the Consumers. > > More generally, OAuth creates a freely-implementable and generic methodology for API authentication. > > [name=[OAuth Core 1.0](https://oauth.net/core/1.0/)] 舊方法造成的問題們: - 第三方程式必須儲存 Resource Owner 的帳號密碼,通常是明文儲存。 - Server 必須支援密碼認證,即使密碼有天生的資訊安全上的弱點。 - 無法限制第三方程式可以拿取 Resource 的時效與範圍。 - Resource Owner 無法只撤回單一個第三方程式的存取權,而且必須要改密碼才能撤回。 - 任何第三方程式被破解,就會導致使用該密碼的所有資料被破解。 ## Definitions ### 1.0 - **Service Provider** 估狗大大 A web application that allows access via OAuth. - **User** 人類 An individual who has an account with the Service Provider. - **Consumer** 第三方服務 A website or application that uses OAuth to access the Service Provider on behalf of the User. - **Protected Resource(s)** 估狗大大的小弟 Data controlled by the Service Provider, which the Consumer can access through authentication. ### 2.0 - **Resource Owner** 人類 An entity capable of granting access to a protected resource. When the resource owner is a person, it is referred to as an end-user. - **Resource Server** API The server hosting the protected resources, capable of accepting and responding to protected resource requests using access tokens. - **Client** 第三方服務 App An application making protected resource requests on behalf of the resource owner and with its authorization. The term "client" does not imply any particular implementation characteristics (e.g., whether the application executes on a server, a desktop, or other devices). - **Authorization Server** 老大 The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization. > Where OAuth 2.0 defines four roles, (client, authorization server, resource server, and resource owner,) OAuth 1 uses a different set of terms for these roles. The OAuth 2.0 “client” is known as the “consumer,” the “resource owner” is known simply as the “user,” and the “resource server” is known as the “service provider”. OAuth 1 also does not explicitly separate the roles of resource server and authorization server. > > [name=[Differences Between OAuth 1 and 2](https://www.oauth.com/oauth2-servers/differences-between-oauth-1-2/)] ## Request URLs / Endpoints ### 1.0 - **Request Token URL** The URL used to obtain an unauthorized Request Token. - **User Authorization URL** The URL used to obtain User authorization for Consumer access. - **Access Token URL** The URL used to exchange the User-authorized Request Token for an Access Token. ### 2.0 Resource Server 上面並沒有定義任何 Endpoints ,這是因為取得 Access Token 的流程與 Resource Server 無關, Resource Server 只需要認 Access Token 並且向 Authorization Server 驗證 Token 合法就行了。 #### Authorization endpoint Used by the client to obtain authorization from the resource owner via user-agent redirection. 給 Client 從 Resource Owner 取得 Authorization Grant 用。 只有 Authorization Code Grant Flow 和 Implicit Grant Flow 才會使用到。 ``` # required response_type: code, # 求 Authorization Code (Authorization Code Flow) token, # 求 Access Token (Implicit Flow) ... # 為 extension client_id: ... # optinal redirect_uri: ... scope: ... # 指定存取範圍 # recommended state: ... # 維持「使用者之前在看 X 頁面」這個狀態 ``` #### Redirection endpoint Used by the authorization server to return responses containing authorization credentials to the client via the resource owner user-agent. Authorization Server 在完成與 Resource Owner 的互動之後(認證 Resource Owner 、提示 Client 要請求授權之類的),會把 Resource Owner 的 User-Agent 轉回 Cilent ,這個轉回去的目標就是 Redirection Endopoint 。 只有 Authorization Code Flow 和 Implicit Flow 才會使用到。 會要求設定 Redirection Endpoint,是為了防止壞人利用 Authorization Endopint 做為 open redirector。 如果 HTML 直接在 Redirection Request 輸出的話,任何 script 都可以拿到 Redirection URI 及包含在其中的 credentials 。 因此有這些建議: - Client 應該直接從 URI 裡面解出 credentials ,並且馬上 redirect 到別的地方以防外洩。 - Client 不應該在 Redirection Response 裡面載入第三方 script (Analytics 、社交網站、廣告等)。 - 若第三方 script 無法避免,則 Client 必須確保自己的 script 先跑,先把 credentials 解出來,並且移除 credentials 。 #### Token endpoint Used by the client to exchange an authorization grant for an access token, typically with client authentication. Client 用來拿取 Access Token 的,需要出示 Authorization Grant 或 Refresh Token。 只有 Implicit Grant Type 不使用,因為這個流程的 Access Token 是直接在 Authorization Endpoint 那邊就直接給了。 ``` # required grant_type: authorization_code, # 用 Authorization Code 求 Access Token (Authorization Code Grant Flow) password, # 用 Resorce Owner Password Credentials 求 Access Token (Resource Owner Password Credentials Grant Flow) client_credentials, # 用 Client Credentials 求 Access Token (Client Credentials Grant Flow) refresh_token, # 用 Refresh Token 換發 Access Token # recommend state: ... # optinal scope: ... ``` ## Authenticating with OAuth ![](https://i.imgur.com/0A3Nza9.png) ![](https://i.imgur.com/xyWSsFf.png) ![](https://i.imgur.com/t9H5Q0e.png) - 取得 Authorization Code 之後,要從 server POST 到 Service Provider 換 token,如此一來,不管是瀏覽器或用戶本身都無法得知 token,就算你的用戶被人在瀏覽器或電腦中安裝了木馬也無法得知,再加上 token 有期限,因此相對安全。 ## [Authorization Grant](https://tools.ietf.org/html/rfc6749#section-1.3) ### Authorization Code Grant Flow ``` +----------+ | Resource | | Owner | | | +----------+ ^ | (B) +----|-----+ Client Identifier +---------------+ | -+----(A)-- & Redirection URI ---->| | | User- | | Authorization | | Agent -+----(B)-- User authenticates --->| Server | | | | | | -+----(C)-- Authorization Code ---<| | +-|----|---+ +---------------+ | | ^ v (A) (C) | | | | | | ^ v | | +---------+ | | | |>---(D)-- Authorization Code ---------' | | Client | & Redirection URI | | | | | |<---(E)----- Access Token -------------------' +---------+ (w/ Optional Refresh Token) ``` ### Implict Grant Flow ``` +----------+ | Resource | | Owner | | | +----------+ ^ | (B) +----|-----+ Client Identifier +---------------+ | -+----(A)-- & Redirection URI --->| | | User- | | Authorization | | Agent -|----(B)-- User authenticates -->| Server | | | | | | |<---(C)--- Redirection URI ----<| | | | with Access Token +---------------+ | | in Fragment | | +---------------+ | |----(D)--- Redirection URI ---->| Web-Hosted | | | without Fragment | Client | | | | Resource | | (F) |<---(E)------- Script ---------<| | | | +---------------+ +-|--------+ | | (A) (G) Access Token | | ^ v +---------+ | | | Client | | | +---------+ ``` ### Resource Owner Password Credentials Grant Flow ``` +----------+ | Resource | | Owner | | | +----------+ v | Resource Owner (A) Password Credentials | v +---------+ +---------------+ | |>--(B)---- Resource Owner ------->| | | | Password Credentials | Authorization | | Client | | Server | | |<--(C)---- Access Token ---------<| | | | (w/ Optional Refresh Token) | | +---------+ +---------------+ ``` ### Client Credentials Flow ``` +---------+ +---------------+ | | | | | |>--(A)- Client Authentication --->| Authorization | | Client | | Server | | |<--(B)---- Access Token ---------<| | | | | | +---------+ +---------------+ ``` ## Refresh 用來向 Authorization Server 重新取得一個新的 Access Token 的 Token ,像是現有的 Access Token 過期而無效,或是權限不足,需要更多 scopes 才能存取別的 Resource。在概念上,Refresh Token 代表了 Resource Owner 授權 Client 重新取得新的 Access Token 而不需要再度請求 Resource Owner 的授權。Client 可以自動做這件事,例如 Access Token 過期了,自動拿新的 Token,來讓應用程式的流程更順暢。 需注意新取得的 Access Token 時效可能比以前短、或比 Resource Owner 給的權限更少。 Authorization Server 不一定要核發 Refresh Token ,但若要核發,必須在核發 Access Token 的時候一併合發。 ``` +--------+ +---------------+ | |--(A)------- Authorization Grant --------->| | | | | | | |<-(B)----------- Access Token -------------| | | | & Refresh Token | | | | | | | | +----------+ | | | |--(C)---- Access Token ---->| | | | | | | | | | | |<-(D)- Protected Resource --| Resource | | Authorization | | Client | | Server | | Server | | |--(E)---- Access Token ---->| | | | | | | | | | | |<-(F)- Invalid Token Error -| | | | | | +----------+ | | | | | | | |--(G)----------- Refresh Token ----------->| | | | | | | |<-(H)----------- Access Token -------------| | +--------+ & Optional Refresh Token +---------------+ ``` ## 差異 - 簡化 Signatures ```shell $ curl --get 'https://api.twitter.com/1.1/statuses/show.json' \ --data 'id=210462857140252672' \ --header 'Authorization: OAuth oauth_consumer_key="xRhHSKcKLl9VF7fbyP2eEw", oauth_nonce="33ec5af28add281c63db55d1839d90f1", oauth_signature="oBO19fJO8imCAMvRxmQJsA6idXk%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1471026075", oauth_token="12341234-ZgJYZOh5Z3ldYXH2sm5voEs0pPXOPv8vC0mFjMFtG", oauth_version="1.0"' ↓ $ curl https://api.example.com/profile -H "Authorization: Bearer XXXXXXXXXXX" ``` - 具有長期授權的短期令牌 ## 參考資料 - [OAuth Core 1.0](https://oauth.net/core/1.0/) - [OAuth 2.0](https://tools.ietf.org/html/rfc6749) - [OAuth 2.0 筆記 / Yu-Cheng Chuang](https://blog.yorkxin.org/2013/09/30/oauth2-1-introduction.html) # API Key - API 金鑰適用於專案,驗證則用於使用者 ![](https://i.imgur.com/RCS055b.png) - API 金鑰的安全性不如驗證憑證,因為用戶端可存取 API 金鑰,這使得有心人士更容易竊取 API 金鑰 ## 使用時機 - 封鎖匿名流量。如果應用程式開發人員須與 API 生產者合作,以便偵測及修正問題,或是顯示應用程式的使用狀況,API 金鑰可為 API 生產者識別應用程式的流量。 - 掌控對 API 發出的呼叫次數。 - 在 API 流量中找出使用模式。 - 依 API 金鑰篩選記錄。 無法用於以下用途: - 識別個別使用者:API 金鑰無法識別使用者,只能識別專案。 - 安全的授權。 - 識別專案建立者。 ## 參考資料 - [API 金鑰的使用原因與時機 / OpenAPI](https://cloud.google.com/endpoints/docs/openapi/when-why-api-key?hl=zh-tw#security_of_api_keys) # HMAC 金鑰雜湊訊息鑑別碼 Hash-based message authentication code,是一種通過特別計算方式之後產生的訊息鑑別碼(MAC),使用密碼雜湊函式,同時結合一個加密金鑰。它可以用來保證資料的完整性,同時可以用來作某個訊息的身分驗證。 > MAC:經過特定演算法後產生的一小段資訊,檢查某段訊息的完整性,以及作身分驗證。 > > ![](https://i.imgur.com/LrZW4A6.png) > 密碼雜湊函式:被認為是一種單向函式,也就是說極其難以由雜湊函式輸出的結果,回推輸入的資料是什麼。 > 訊息(message)→ 訊息摘要(message digest)或摘要(digest)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully