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

ReactJS集成Google登录后重定向失败及CSP问题求助

React集成Google登录后重定向失败、CSP警告及404问题解决

问题描述

在ReactJS客户端集成Google登录按钮后,登录成功无法从https://accounts.google.com/...重定向回本地客户端地址http://localhost:5000,浏览器控制台出现多条Content Security Policy(CSP)忽略警告,POST请求http://localhost:3000/login返回404 Not Found,同时无法看到handleCredentialResponse回调的控制台日志。

控制台日志

Navigated to http://localhost:3000/login
Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “http:” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “http:” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified
Content Security Policy: Ignoring “http:” within script-src: ‘strict-dynamic’ specified
POSThttp://localhost:3000/login
[HTTP/1.1 404 Not Found 17ms]

Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:3000/favicon.ico (“default-src”).

GoogleAuth组件代码

import { useEffect, useRef } from 'react'

const loadScript = (src) =>
    new Promise((resolve, reject) => {
        if (document.querySelector(`script[src="${src}"]`)) return resolve()
        const script = document.createElement('script')
        script.src = src
        script.onload = () => resolve()
        script.onerror = (err) => reject(err)
        document.body.appendChild(script)
    })

const GoogleAuth = () => {
    const googleButton = useRef(null);

    useEffect(() => {
        const src = 'https://accounts.google.com/gsi/client'
        const id = "<I gave valid ClientID>"

        loadScript(src)
            .then(() => {
                /*global google*/
                console.log(google)
                google.accounts.id.initialize({
                    client_id: id,
                    ux_mode: "redirect",
                    login_uri: window.location,
                    callback: handleCredentialResponse,
                })
                google.accounts.id.renderButton(
                    googleButton.current,
                    { theme: 'outline', size: 'large' }
                )
            })
            .catch(console.error)

        return () => {
            const scriptTag = document.querySelector(`script[src="${src}"]`)
            if (scriptTag) document.body.removeChild(scriptTag)
        }
    }, [])

    function handleCredentialResponse(response) {
        console.log("Encoded JWT ID token: " + response.credential);
    }

    return (
        <div ref={googleButton}></div>
    )
}

export default GoogleAuth

解决方案

1. 修正回调与重定向逻辑

  • 当前设置ux_mode: "redirect"时,不会触发前端handleCredentialResponse回调,Google会直接通过POST请求将凭证发送到login_uri指定的地址,你看到的404是因为http://localhost:3000/login没有对应的后端接口。
  • 若想使用前端回调处理(看到handleCredentialResponse日志),将ux_mode改为"popup"并移除login_uri:
    google.accounts.id.initialize({
        client_id: id,
        ux_mode: "popup",
        callback: handleCredentialResponse,
    })
    
  • 若坚持使用redirect模式,需在后端(如http://localhost:5000/login)实现接收凭证的接口,并将login_uri设为该后端地址,而非前端的window.location。

2. 处理CSP警告

  • 控制台的CSP警告是因为配置中同时使用strict-dynamic和unsafe-inline/https:/http:,根据CSP规则,strict-dynamic会忽略这些冗余配置,属于正常提示。若要消除警告:
    • 保留strict-dynamic,移除script-src中的'unsafe-inline'、https:、http:
    • 确保CSP允许加载Google脚本:script-src 'strict-dynamic' https://accounts.google.com;
  • 针对favicon.ico的错误,在CSP的default-src或img-src中添加http://localhost:3000(本地开发场景)。

3. 修正重定向地址不匹配

  • 检查Google Cloud控制台中,OAuth 2.0客户端ID的已授权重定向URI是否添加了http://localhost:5000(或对应的回调地址)
  • 确保login_uri(若用redirect模式)设置为正确的http://localhost:5000/login,而非当前前端地址。

4. 组件代码优化

  • 移除useEffect中的脚本清理逻辑:Google GSI脚本无需卸载时删除,重复加载会自动复用已存在的脚本,清理反而可能导致后续渲染出错。
  • 确认client_id无多余引号或占位符,确保有效。

内容的提问来源于stack exchange,提问作者Govind Avireddi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:45:31