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

Passport对接Google登录遇两类错误:缺authorizationURL及AccessToken获取失败

问题解决方案

问题1:passport-oauth2 提示 "OAuth2Strategy requires a authorizationURL option"

passport-oauth2是通用OAuth2策略,没有内置特定服务商的端点信息,所以必须手动指定Google OAuth2的核心端点:

  • authorizationURL:https://accounts.google.com/o/oauth2/v2/auth
  • tokenURL:https://oauth2.googleapis.com/token

修改后的策略代码:

import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Profile } from "passport";
import { VerifyCallback, Strategy } from "passport-oauth2";

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy) {
    constructor() {
        super({
            clientID: "你的Google客户端ID",
            clientSecret: "你的Google客户端密钥",
            authorizationURL: "https://accounts.google.com/o/oauth2/v2/auth",
            tokenURL: "https://oauth2.googleapis.com/token",
            callbackURL: "http://localhost:3000/google/callback",
            scope: ["email", "profile"]
        })
    }

    async validate(accessToken: string, refresToken: string, profile: Profile, done: VerifyCallback) {
      done(null, profile);
    }
}

问题2:passport-google-oauth20 提示 "Failed to obtain access token"

这个错误通常由以下原因导致,逐一排查:

  • 客户端凭证错误:确认从Google Cloud控制台获取的clientID和clientSecret完全正确,无拼写错误或多余空格。
  • 回调URL不匹配:在Google Cloud控制台的OAuth 2.0客户端ID设置中,"已获授权的重定向URI"必须与代码中的callbackURL完全一致(包括协议、端口、路径)。
  • 项目配置缺失:
    • 确保项目已启用Identity Toolkit API(或相关Google OAuth依赖的API)。
    • 检查OAuth同意屏幕状态:若为测试状态,只有添加到测试用户列表的账号才能正常登录。
  • 网络问题:若服务器在国内,需确保能正常访问Google OAuth相关端点,避免网络拦截导致请求失败。

推荐的passport-google-oauth20策略代码:

import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Profile, Strategy } from "passport-google-oauth20";

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
    constructor() {
        super({
            clientID: "你的Google客户端ID",
            clientSecret: "你的Google客户端密钥",
            callbackURL: "http://localhost:3000/google/callback",
            scope: ['email', 'profile'],
        });
    }

    async validate(accessToken: string, refreshToken: string, profile: Profile) {
        return {
            id: profile.id,
            email: profile.emails[0].value,
            name: profile.displayName,
        };
    }
}

内容的提问来源于stack exchange,提问作者Rahul Mane

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:35:28