---
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



- 取得 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 金鑰適用於專案,驗證則用於使用者

- 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:經過特定演算法後產生的一小段資訊,檢查某段訊息的完整性,以及作身分驗證。
>
> 
> 密碼雜湊函式:被認為是一種單向函式,也就是說極其難以由雜湊函式輸出的結果,回推輸入的資料是什麼。
> 訊息(message)→ 訊息摘要(message digest)或摘要(digest)