APP練習-Spotify API (1)申請與設定

Huei
5 min readJan 10, 2021

--

申請 Spotify的開發者權限,完成應用程式設定與初探 API 授權機制。

參考官網說明 Spotify API 的使用,需要:

  1. 註冊應用程式
  2. 遵循 Spotify 授權流程

— — — —

首先,至 Spotify Developer 頁面註冊應用程式,申請 Spotify 的開發者權限,取得 Client IDClient Secret :

1. Spotify 開發者申請截圖
2. 取得 Client ID & Secret

client_id 為公開資訊,用來辨識應用程式,client_secret 屬於私密資訊,需妥善保存。

3. Redirect URIs 設定

Redirect URIs 白名單,此設定為非必要,其作用是當應用系統需取得使用者於 Spotify 的相關資訊時,透過 Spotify 驗證服務自動重定向的網址,用來接收驗證結果回應 (code or access token)。

— — — — — — — — — — — — —

Redirect URIs 白名單可輸入一個或多個,iOS 填寫的 URI 範例如 app 名稱為 My Awesome App,URI 可為 my-awesome-app-login://callback 或awesomeprotocol123://returnafterlogin。

與之呼應的 app URL Scheme 設定,位於專案的 info/URL Types,其中 URL Schemes 只需填寫 :// 以前的 protocol 資訊。

URL Scheme 設定

完成註冊後,接著參考 Spotify 的 app 授權機制,分為以下兩種權限

  • App Authorization: Spotify 授權 app 訪問 Spotify 平台,訪問方式可透過 API、SDKs 與 Widgets方式。(需要 client_id & client_secret)
  • User Authorization: 使用者授權 app 訪問使用者的個人資訊,授權透過OAuth 2.0 認證。(需要導引使用者登入 Spotify,授權 app)
Spotify authorization process

對於以上兩種權限的授權,Spotify 支援 OAuth 2.0 機制(官方建議 PKCE ):

Authorization flows
  • Authorization Code Flow:導引使用者至 Spotify 認證網頁,他們可以在其中選擇授予 app 訪問其數據的權限。
  • Authorization Code Flow with Proof Key for Code Exchange (PKCE):增強 Authorization Code Flow,透過交換授權碼,換取 token。
  • Client Credentials Flow:使用 client_id 與 client_secret 取得 token。
  • Implicit Grant Flow:適用於 JavaScript 和網頁端應用,token 效期短。

對授權流程有基本概念後,為感受一下 Spotify API 授權功能,我先嘗試以 Client Credentials Flow 取得授權,後續再依據 PKCE 流程開發。

** * 補充說明,訪問 Spotify 平台是透過 API 方式,而非 SDKs 的原因為,SDKs 方式需於同台手機上安裝 Spotify app,而模擬器似乎無 APP Store 可安裝 app;另一方面為了熟悉 swift 呼叫 API 的語法,故選擇以 API 串接。

Requirements: A physical iOS device is needed to install the Spotify app.

參考 Spotify 官網上 Client Credentials Flow 的 API 範例

client-credentials-flow authorization api

依據 API 規格回傳資訊包含 access_token — — 此為取得授權的目的,之後將透過此 token 獲取各種 API 資訊。因 token 如此重要,故儲存至 keychain

iOS 儲存方式

最後,整合上述資訊 Demo 如下 :

access token 儲存

下一篇,將調整授權方式,嘗試以 PKCE 流程進行開發 — — 加入使用者登入 Spotify 授權 app 動作,以獲取訪問使用者資訊的權限。

— — — — — — — — —

程式碼如下:

--

--