开发者问题收集

React 和 Sanity 无法使用谷歌身份验证

2022-10-18
609

我制作了一个 React 和 Sanity 项目。

但无法通过 Google 进行身份验证。如何通过这种安全方式解决?(而不是使用“口香糖”)

我收到以下消息: 未捕获的 TypeError:无法解构“response.profileObj”的属性“name”,因为它未定义。

这导致我没有得到 profileObj,因此也无法破坏 name 属性...

相反,我得到了这个对象:

{
    "error": "idpiframe_initialization_failed",
    "details": "You have created a new client application that uses libraries for user authentication or authorization that will soon be deprecated. New clients must use the new libraries instead; existing clients must also migrate before these libraries are deprecated. See the [Migration Guide](https://developers.google.com/identity/gsi/web/guides/gis-migration) for more information."
}

Login.js

import React from 'react';
import GoogleLogin from 'react-google-login';
import { useNavigate } from 'react-router-dom';
import { FcGoogle } from 'react-icons/fc';
import shareVideo from '../assets/share.mp4';
import logo from '../assets/logowhite.png';

import { client } from '../client';

const Login = () => {
  const navigate = useNavigate();
  const responseGoogle = (response) => {
      console.log(response)
    localStorage.setItem('user', JSON.stringify(response.profileObj));
    const { name, googleId, imageUrl } = response.profileObj;
    const doc = {
      _id: googleId,
      _type: 'user',
      userName: name,
      image: imageUrl,
    };
    client.createIfNotExists(doc).then(() => {
      navigate('/', { replace: true });
    });
  };

  return (
    <div className="flex justify-start items-center flex-col h-screen">
      <div className=" relative w-full h-full">
        <video
          src={shareVideo}
          type="video/mp4"
          loop
          controls={false}
          muted
          autoPlay
          className="w-full h-full object-cover"
        />

        <div className="absolute flex flex-col justify-center items-center top-0 right-0 left-0 bottom-0    bg-blackOverlay">
          <div className="p-5">
            <img src={logo} width="130px" />
          </div>

          <div className="shadow-2xl">
            <GoogleLogin
              clientId={`${process.env.REACT_APP_GOOGLE_API_TOKEN}`}
              render={(renderProps) => (
                <button
                  type="button"
                  className="bg-mainColor flex justify-center items-center p-3 rounded-lg cursor-pointer outline-none"
                  onClick={renderProps.onClick}
                  disabled={renderProps.disabled}
                >
                  <FcGoogle className="mr-4" /> Sign in with google
                </button>
              )}
              onSuccess={responseGoogle}
              onFailure={responseGoogle}
              cookiePolicy="single_host_origin"
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;

package.json

{
  "name": "xxxx",
  "private": true,
  "version": "1.0.0",
  "description": "xxxx",
  "main": "package.json",
  "author": "xxxx",
  "license": "UNLICENSED",
  "scripts": {
    "start": "sanity start",
    "build": "sanity build"
  },
  "keywords": [
    "sanity"
  ],
  "dependencies": {
    "@sanity/base": "^2.34.0",
    "@sanity/core": "^2.34.0",
    "@sanity/default-layout": "^2.34.0",
    "@sanity/default-login": "^2.34.0",
    "@sanity/desk-tool": "^2.34.1",
    "@sanity/eslint-config-studio": "^2.0.0",
    "@sanity/vision": "^2.34.0",
    "eslint": "^8.6.0",
    "prop-types": "^15.7",
    "react": "^17.0",
    "react-dom": "^17.0",
    "styled-components": "^5.2.0"
  },
  "devDependencies": {}
}
3个回答

您需要解码 JWT 令牌。它位于响应的“credential”属性内。只需安装 jwt-decode 包: npm i jwt-decode

然后导入它并在 Login.jsx 中使用它:

import jwt_decode from 'jwt-decode';

const USER = 'pint-clone-user';

// use jwt_decode()
 const responseGoogle = (response) => {
    console.log(response);
    localStorage.setItem(USER, JSON.stringify(response.credential));

    const { name, jti, picture } = jwt_decode(response.credential); // here
    console.log({ name, jti, picture });

    // save user as a Sanity 'user' document
    const doc = {
      _id: jti,               // here
      _type: 'user',
      userName: name,
      image: picture,    // here
    };

    client.createIfNotExists(doc).then(() => {
      navigate('/', { replace: true });
    });
  };
Code Concept
2022-10-28

我在这里进行同一项目,并且有同样的错误。也许由于库的这种限制。

有些人在NPM上发现了漏洞,我认为ID应该是一个主题,因为它们会阻止NPM访问Google Cloud,现在它公共😕

Luiz Santos
2022-10-18

是因为Google已更新了政策。 您应该尝试一下。 但是,在这样做之前

Muhammad Hammad
2022-12-12