You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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_code
  • code: 授权请求返回的授权码
  • redirect_uri: 和授权请求里的完全一致(用AuthSession.makeRedirectUri()生成的那个)
  • client_id: 你的Spotify客户端ID
  • code_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 15:45:31