Type something to search...
玩玩看 Spotify 的 Authorization Code Flow with PKCE

玩玩看 Spotify 的 Authorization Code Flow with PKCE

  • Web
  • 20 Sep, 2020

看到 Spotify 有支援另外一種 Authorization Code Flow,叫做 Authorization Code Flow with Proof Key for Code Exchange (PKCE),來玩玩看

Authorization Code Flow with PKCE 跟 Authorization Code Flow 的差異在於。為了怕使用者的 code 被中間人竊取而拿去取得 access token 來盜用,多了一點驗證機制,讓取得 access token 時需要跟 Spotify 證明:我是剛剛那個跟你要 code 的使用者。

因此在「取得 code 階段」,多傳了code_challenge_methodcode_challenge。並在「取得 access token」階段,多傳了code_verifier

code_verifier 是一組隨機產生的亂碼,code_challenge 是由 code_verifier 經過 SHA256 產生的 digest,並用 Base 64 encode 的字串。

在 Spotify 收到請求 access token 的需求時,會用 code_verifier 來驗證這組的 code 原始請求所附帶的 code_challenge 是不是能由這組 code_verifier 來產生,如果可以的話,就代表這的請求是來自正確的使用者。原因是只靠code_challenge 是無法反推回 code_verifier 的,所以能拿出 code_verifier 就表示你是產生 code_challenge 的使用者。

產生 code_verifiercode_challenge 的 Ruby 腳本可以參考:

require 'securerandom'
require 'digest'
require 'base64'
code_verifier = SecureRandom.urlsafe_base64(96)
puts "code_verifier: #{code_verifier}"
code_challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(code_verifier), padding: false)
puts "code_challenge: #{code_challenge}"

相關文章

Share :

Related Posts

Fetch API 沒有傳送 cookies
Fetch API 沒有傳送 cookies

最近遇到一個案例,用戶明明有登入,但是打 API 時,卻因為沒有登入而噴錯。 在追查 HTTP Request/Response 時,眼尖的同事發現 Request Headers 根本沒有帶上 cookies,所以伺服器因為沒有 session 登入的資訊,所以才會當成 Client 端還沒登入。但奇怪的是 Client 端的網頁明明就是登入狀態。還有另一個線索是用戶的 Chrome 瀏覽器是

read more
Chrome, AWS S3 and CORS
Chrome, AWS S3 and CORS

前陣子與公司的其他夥伴一起找出了偶發的 CORS 原因,紀錄一下 如果一個網站內有包含對同一個 URL 的載入,但是有兩種方式,一種是從 HTML document 載入,另一種是用 xhr 存取,並且 Chome 有開啟 cache,就有可能會遇到。 重現問題 例如下面這個簡單的範例,用兩種方式從 AWS cloudfont 抓取圖片,CDN 的來源是 AWS S3

read more
玩玩看 KKBOX 與 Spotify 的 OAuth 2.0
玩玩看 KKBOX 與 Spotify 的 OAuth 2.0

心血來潮想玩看看 KKBOX 的 Open API,也一起測試了 Spotify 的部分。這次主要是試試看 OAuth 2.0 Authorization Code Flow 的授權流程,過程都是利用 Postman 來操作。 <LinkCard url="https://developer.spotify.com/documentation/general/guides/authoriza

read more