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

Spotify认证出现state_mismatch错误的排查求助

Spotify认证出现state_mismatch错误的排查求助

大家好,我最近做Spotify相关开发时碰到个头疼的问题:点击「用Spotify认证」按钮后,跳转的URL里直接抛出了state_mismatch错误。

我已经做了这些核对:

  • 开发者后台设置的回调URI和代码里的redirect_uri完全一致,都是http://localhost:8888/callback/
  • 发起认证请求时生成的state值,和回调返回的state值我也反复核对过,确实是相同的
  • client_id、client_secret这类基础配置也确认过没有填错

之前有一段逻辑类似的代码是能正常完成Spotify认证的,现在的流程看起来和之前没差,但就是出了这个问题,实在摸不着头绪。下面是我当前的核心代码片段,麻烦大家帮忙看看有没有遗漏或者错误的地方:

基础配置部分

const client_id = ''; // 我的Client ID
const client_secret = ''; // 我的Client Secret
const redirect_uri = 'http://localhost:8888/callback/';
const openaiApiKey = '';

const spotifyApi = new SpotifyWebApi({ 
  clientId: client_id,
  clientSecret: client_secret 
});

const chatGpt = new openai.OpenAIApi(openaiApiKey);
const sentiment = new Sentiment();

const stateKey = 'spotify_auth_state';

Express Session与认证相关逻辑

const session = require('express-session');

app.use(session({
  secret: 'your_secret_key',
  resave: true,
  saveUninitialized: true
}));

let access_token;
let refresh_token;

app.use(express.static(__dirname + '/public'))

const checkAccessTokenValidity = (req, res, next) => {
  if (!access_token) {
    return res.status(401).send('Access token is missing.');
  }

  const options = {
    hostname: 'api.spotify.com',
    path: '/v1/me',
    headers: { 'Authorization': 'Bearer ' + access_token },
    method: 'GET'
  };

  const accessTokenReq = http.request(options, (response) => {
    if (response.statusCode === 401) {
      // Access token expired, refresh the token
      refreshtoken();
    }
    next();
  });

  accessTokenReq.on('error', (error) => {
    console.error('Error checking access token validity:', error);
    res.status(500).send('Internal server error');
  });

  accessTokenReq.end();
};

会不会是session的配置或者token校验的逻辑影响了state的验证?或者我在Spotify认证流程里漏掉了什么关键步骤?麻烦各位大佬帮忙分析一下,谢谢!

备注:内容来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 07:54:35