You need to enable JavaScript to run this app. 如何将Twitch自定义OAuth与firebase.auth().signInWithRedirect集成
优惠活动
大模型
产品
解决方案
定价
更多

如何将Twitch自定义OAuth与firebase.auth().signInWithRedirect集成

我参考Instagram 示例搭建了Twitch OAuth集成逻辑,目前可以通过该示例提供的popup.html页面完成应用登录。
以下是我适配后的代码:

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cookieParser = require('cookie-parser');
const crypto = require('crypto');
const { AuthorizationCode } = require('simple-oauth2');
const fetch = require('node-fetch');

// Firebase Setup
const admin = require('firebase-admin');
// @ts-ignore
const serviceAccount = require('./service-account.json');
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`,
});

const OAUTH_REDIRECT_URI = `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/popup.html`;;
const OAUTH_SCOPES = 'user:read:email';

/**
 * Creates a configured simple-oauth2 client for Twitch.
 */
function twitchOAuth2Client() {
  // Twitch OAuth 2 setup
  // TODO: Configure the `twitch.client_id` and `twitch.client_secret` Google Cloud environment variables.
  const credentials = {
    client: {
      id: functions.config().twitch.client_id,
      secret: functions.config().twitch.client_secret,
    },
    auth: {
      tokenHost: 'https://id.twitch.tv',
      tokenPath: '/oauth2/token',
      authorizePath: '/oauth2/authorize',
    },
    options: {
      bodyFormat: 'json',
      authorizationMethod: 'body',
    },
  };
  return new AuthorizationCode(credentials);
}

/**
 * Redirects the User to the Twitch authentication consent screen. Also the 'state' cookie is set for later state
 * verification.
 */
exports.redirect = functions.https.onRequest((req, res) => {
  const authorizationCode = twitchOAuth2Client();

  cookieParser()(req, res, () => {
    const state = req.cookies.__session || crypto.randomBytes(20).toString('hex');
    console.log('Setting verification state:', state);
    res.cookie('__session', state.toString(), { maxAge: 3600000, httpOnly: true });
    const redirectUri = authorizationCode.authorizeURL({
      redirect_uri: OAUTH_REDIRECT_URI,
      scope: OAUTH_SCOPES,
      state: state,
    });
    console.log('Redirecting to:', redirectUri);
    res.redirect(redirectUri);
  });
});

/**
 * Exchanges a given Twitch auth code passed in the 'code' URL query parameter for a Firebase auth token.
 * The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie.
 * The Firebase custom auth token, display name, photo URL and Twitch acces token are sent back in a JSONP callback
 * function with function name defined by the 'callback' query parameter.
 */
exports.token = functions.https.onRequest((req, res) => {
  const authorizationCode = twitchOAuth2Client();

  try {
    cookieParser()(req, res, async () => {
      try {
        console.log('Received verification state:', req.cookies.__session);
        console.log('Received state:', req.query.state);
        if (!req.cookies.__session) {
          throw new Error(
            'State cookie not set or expired. Maybe you took too long to authorize. Please try again.'
          );
        } else if (req.cookies.__session !== req.query.state) {
          throw new Error('State validation failed');
        }
      } catch (error) {
        return res.jsonp({ error: error.toString() });
      }

      let accessToken;
      try {
        console.log('Received auth code:', req.query.code);
        const options = {
          client_id: functions.config().twitch.client_id,
          client_secret: functions.config().twitch.client_secret,
          code: req.query.code,
          grant_type: 'authorization_code',
          redirect_uri: OAUTH_REDIRECT_URI,
        };
        console.log('Asking token with options', JSON.stringify(options));
        accessToken = await authorizationCode.getToken(options);
        console.log('Auth code exchange result received');

        const twitchUser = await getTwitchUser(accessToken.toJSON().access_token);

        // Create a Firebase account and get the Custom Auth Token.
        const firebaseToken = await createFirebaseAccount(twitchUser);

        // Serve an HTML page that signs the user in and updates the user profile.
        return res.jsonp({ token: firebaseToken });
      } catch (error) {
        return res.jsonp({ error: error.toString() });
      }
    });
  } catch (error) {
    return res.jsonp({ error: error.toString() });
  }
});

/**
 * Creates a Firebase account with the given user profile and returns a custom auth token allowing
 * signing-in this account.
 *
 * @returns {Promise<string>} The Firebase custom auth token in a promise.
 */
async function createFirebaseAccount(twitchUser) {
  // The UID we'll assign to the user.
  const uid = `twitch:${twitchUser.id}`;

  // Save the access token to the Firebase Database.
  const db = admin.firestore();
  const databaseTask = db.collection('users').doc(uid).set(twitchUser);

  // Create or update the user account.
  const userCreationTask = admin
    .auth()
    .updateUser(uid, {
      displayName: twitchUser['display_name'],
      photoURL: twitchUser['profile_image_url'],
      email: twitchUser['email'],
    })
    .catch((error) => {
      // If user does not exists we create it.
      if (error.code === 'auth/user-not-found') {
        return admin.auth().createUser({
          uid: uid,
          displayName: twitchUser['display_name'],
          photoURL: twitchUser['profile_image_url'],
          email: twitchUser['email'],
        });
      }
      throw error;
    });

  // Wait for all async task to complete then generate and return a custom auth token.
  await Promise.all([userCreationTask, databaseTask]);
  // Create a Firebase custom auth token.
  const token = await admin.auth().createCustomToken(uid);
  console.log('Created Custom token for UID "', uid, '" Token:', token);
  return token;
}

async function getTwitchUser(accessToken) {
  console.log('Fetching Twitch user with access_token', accessToken);
  try {
    const response = await fetch('https://api.twitch.tv/helix/users', {
      method: 'GET',
      headers: {
        'Client-Id': functions.config().twitch.client_id,
        Authorization: 'Bearer ' + accessToken,
      },
    });
    const data = await response.json();
    return { ...data.data[0], access_token: accessToken };
  } catch (error) {
    console.error(error);
  }
}

不过我希望使用目前已用于Facebook、Google登录的firebase.auth().signInWithRedirect()方法实现Twitch登录,但找不到相关文档;查看Facebook 提供方源码后发现其引用了externs.*资源,我不确定如何将其适配到自身需求。目前我已经有两个端点/云函数:_twitchRedirect和_twitchToken,请问该如何操作才能将它们与signInWithRedirect集成?

实现方案
  • 修改Twitch开发者后台配置:将OAuth重定向URI替换为token云函数的公网访问地址,替换原有popup.html的配置值,避免授权回调时触发URI校验失败。
  • 调整token云函数返回逻辑:将原有JSONP返回自定义token的代码,改为重定向到应用内的登录回调页,把生成的Firebase自定义token作为URL参数拼接在重定向地址后。保留原有的state校验、access token交换、Twitch用户信息拉取、Firebase用户创建的全部逻辑不变。
  • 前端触发逻辑调整:将原有的弹窗打开redirect云函数的逻辑,改为直接整页跳转,用户点击Twitch登录按钮后直接进入Twitch授权页,和Google、Facebook登录的跳转体验保持一致。
  • 前端回调逻辑实现:在应用入口或专门的登录回调页面添加判断逻辑:
    • 检查当前URL是否携带自定义token参数
    • 若存在,直接调用firebase.auth().signInWithCustomToken(token)完成登录
    • 登录成功后清除URL中的敏感参数,直接跳转到应用首页,实现和官方signInWithRedirect完全一致的登录流程
  • 源码适配说明:官方SDK中引用externs.*的代码是内置Provider的内部实现,仅用于官方支持的Facebook、Google等身份提供方的底层逻辑,自定义OAuth场景完全不需要修改或适配这部分代码,只要模拟其“整页跳转-回调拿凭证-静默完成登录”的流程,就能达到同等用户体验。
  • 原有代码修正:删除重复引入的admin依赖,去掉OAUTH_REDIRECT_URI末尾多余的分号,避免运行时报错。

内容的提问来源于stack exchange,提问作者Fez Vrasta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.05 23:06:05