如何通过Expo Auth Session获取Spotify的Refresh Token?
在Expo中通过expo-auth-session获取Spotify刷新令牌的正确方式
要拿到Spotify的刷新令牌,核心是两步:添加正确的权限范围和正确调用令牌接口,你之前失败大概率是这两点没做好:
1. 授权请求必须包含offline_access权限
Spotify默认不会返回刷新令牌,必须在授权请求的scopes里明确加上offline_access,否则哪怕用授权码流也拿不到。
示例代码:
import * as AuthSession from 'expo-auth-session'; const discovery = { authorizationEndpoint: 'https://accounts.spotify.com/authorize', tokenEndpoint: 'https://accounts.spotify.com/api/token', }; // 发起授权请求时,scopes里加上offline_access const result = await AuthSession.startAsync({ authUrl: `${discovery.authorizationEndpoint}?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=${encodeURIComponent(AuthSession.makeRedirectUri())}&scope=${encodeURIComponent('user-read-private offline_access')}`, });
2. 用授权码调用令牌接口的正确姿势
调用Spotify的令牌接口时,必须带上所有必填参数,尤其是PKCE的code_verifier(expo-auth-session会自动生成,你需要从授权请求的结果里拿到):
关键参数:
grant_type: 固定为authorization_codecode: 授权请求返回的授权码redirect_uri: 和授权请求里的完全一致(用AuthSession.makeRedirectUri()生成的那个)client_id: 你的Spotify客户端IDcode_verifier: 从AuthSession.startAsync返回的params.codeVerifier获取
调用示例:
if (result.type === 'success') { const { code, codeVerifier } = result.params; const tokenResponse = await fetch('https://accounts.spotify.com/api/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: AuthSession.makeRedirectUri(), client_id: 'YOUR_CLIENT_ID', code_verifier: codeVerifier, }), }); const tokenData = await tokenResponse.json(); // 这里就能拿到refresh_token了 console.log('刷新令牌:', tokenData.refresh_token); }
常见坑点
- 确保你的Spotify开发者后台里配置的
Redirect URI和代码里的完全一致,包括协议(比如exp://开头的) - 不要在前端代码里硬编码
client_secret,Expo原生应用用PKCE流程不需要这个,避免泄露 - 拿到
refresh_token后,用Expo的SecureStore保存,不要存在普通的AsyncStorage里
内容的提问来源于stack exchange,提问作者Jayden Yu
相关产品推荐
相关产品推荐

