MomenSherif / react-oauth

Google OAuth2 using the new Google Identity Services SDK for React 🚀
https://www.npmjs.com/package/@react-oauth/google
MIT License
1.13k stars 141 forks source link

How can i get the user details from this code #346

Open Thirumalakond-Ganesh opened 6 months ago

Thirumalakond-Ganesh commented 6 months ago

import { useGoogleLogin } from '@react-oauth/google';

const login = useGoogleLogin({ onSuccess: tokenResponse => console.log(tokenResponse), });

Output i am getting:- {access_token: 'ya29.a0AXooCgt6w-E0IUzjRPO5uYnhSpS2o5kJoEK0cWiCQ6W…TsaCgYKAZcSARASFQHGX2MiMEc1HD3QuJX2AVIvH7A5Aw0170', token_type: 'Bearer', expires_in: 3599, scope: 'email profile openid https://www.googleapis.com/au…le https://www.googleapis.com/auth/userinfo.email', authuser: '0', …} access_token : "ya29.a0AXooCgt6w-E0IUzjRPO5uYnhSpS2o5kJoEK0cWiCQ6WEMpJq4KW4xs-_lOubdorhj8Cdhf3AfyVFsU6c0IxHigK7WAqP1MYJ-OQdYVkuVlcaVMihQYDcJ4xQ4-PMFAx_qYu58Gl4jtdI7juHPAJf4Icq1-mcCvLnlTsaCgYKAZcSARASFQHGX2MiMEc1HD3QuJX2AVIvH7A5Aw0170" authuser : "0" expires_in : 3599 prompt : "none" scope : "email profile openid https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email" token_type : "Bearer"

actual output i need is:-

aud : "160074142288-8o973fd5lsgdliic5i6ie83aod662gab.apps.googleusercontent.com" azp : "160074142288-8o973fd5lsgdliic5i6ie83aod662gab.apps.googleusercontent.com" email : "mrabhi74744@gmail.com" email_verified : true exp : 1714723617 family_name : "Abhi" given_name : "Mr" iat : 1714720017 iss : "https://accounts.google.com" jti : "4b9458ffefa2a0275d05b52fe80c69f58f767299" name : "Mr Abhi" nbf : 1714719717 picture : "https://lh3.googleusercontent.com/a/ACg8ocKg0az7NVhTLD-8mb0OIzpQISCFY2ehyYTLzL8IK5UM-QW6kA=s96-c" sub : "114964555203191333911"

aniketharx10x commented 6 months ago

hello, try this:

(prerequisite: npm i axios)

import { useGoogleLogin } from '@react-oauth/google';
import axios from 'axios';

const login = useGoogleLogin({
    onSuccess: async (tokenResponse) => {
      try {
        const response = await axios.get(
          'https://www.googleapis.com/oauth2/v3/userinfo',
          {
            headers: { 
              Authorization: `Bearer ${tokenResponse.access_token}` 
            },
          }
        );
        console.log(response.data);
      } catch (err) {
        console.log(err);
      }
    },
  });

I got the user details on the console from this code

Thirumalakond-Ganesh commented 6 months ago

But for me this error came Access to XMLHttpRequest at 'https://www.googleapis.com/oauth2/v3/userinfo' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. Login.js:62 AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}code: "ERR_NETWORK"config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}message: "Network Error"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …}onabort: ƒ handleAbort()onerror: ƒ handleError()onload: nullonloadend: ƒ onloadend()onloadstart: nullonprogress: nullonreadystatechange: nullontimeout: ƒ handleTimeout()readyState: 4response: ""responseText: ""responseType: ""responseURL: ""responseXML: nullstatus: 0statusText: ""timeout: 0upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …}onabort: nullonerror: nullonload: nullonloadend: nullonloadstart: nullonprogress: nullontimeout: null[[Prototype]]: XMLHttpRequestUploadwithCredentials: true[[Prototype]]: XMLHttpRequeststack: "AxiosError: Network Error\n at XMLHttpRequest.handleError (http://localhost:3000/static/js/bundle.js:146504:14)"[[Prototype]]: Error Login.js:50

    GET https://www.googleapis.com/oauth2/v3/userinfo net::ERR_FAILED  How can i fix this and this my code 

    import React, { useState } from "react";

import { Link, useNavigate } from "react-router-dom"; import { InputText } from "primereact/inputtext"; import { Button } from "primereact/button"; import { useForm } from "react-hook-form"; import "../Login/Login.css"; import axios from "axios"; import { SERVER_url } from "../../config"; import { GoogleLogin, useGoogleLogin } from "@react-oauth/google"; import jwtDecode from "jwt-decode"; // Correct import

const Login = () => { axios.defaults.withCredentials = true; const navigate = useNavigate(); const [error, setError] = useState(""); const { handleSubmit, formState: { errors }, register, } = useForm();

const onSubmit = async (data) => { try { const response = await axios.post(${SERVER_url}/login, data); doLogin(response); } catch (error) { setError("An error occurred while logging in"); console.error("Error occurred", error); } };

const doLogin = (response) => { console.log("Response Status:", response.status); console.log("Response Data:", response.data);

if (response.status === 200) {
  setError(""); // Clear any previous error
  localStorage.setItem("token", response.data.jwtToken);
  sessionStorage.setItem("token", response.data.jwtToken);
  navigate("/home");
  console.log("Login successful");
} else {
  setError("Incorrect email or password");
}

};

const login = useGoogleLogin({ onSuccess: async (tokenResponse) => { try { const response = await axios.get( 'https://www.googleapis.com/oauth2/v3/userinfo', { headers: { Authorization: Bearer ${tokenResponse.access_token} }, } ); console.log(response.data); // Handle the response data here, such as logging in the user doLogin({ status: 200, data: { jwtToken: tokenResponse.access_token } }); } catch (err) { console.log(err); } }, onError: (error) => console.log("Login Failed:", error), });

return (

LogIn

{errors.email &&

{errors.email.message}

} {errors.password && (

{errors.password.message}

)} {error &&

{error}

}

Don't have an account yet ?{" "} Sign up here

); };

export default Login;

Thirumalakond-Ganesh commented 6 months ago

Please help me in this

Thirumalakond-Ganesh commented 6 months ago

But I got this error Access to XMLHttpRequest at ' https://www.googleapis.com/oauth2/v3/userinfo' from origin ' http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. Login.js:62 AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}code: "ERR_NETWORK"config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}message: "Network Error"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: true, upload: XMLHttpRequestUpload, …}onabort: ƒ handleAbort()onerror: ƒ handleError()onload: nullonloadend: ƒ onloadend()onloadstart: nullonprogress: nullonreadystatechange: nullontimeout: ƒ handleTimeout()readyState: 4response: ""responseText: ""responseType: ""responseURL: ""responseXML: nullstatus: 0statusText: ""timeout: 0upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …}onabort: nullonerror: nullonload: nullonloadend: nullonloadstart: nullonprogress: nullontimeout: null[[Prototype]]: XMLHttpRequestUploadwithCredentials: true[[Prototype]]: XMLHttpRequeststack: "AxiosError: Network Error\n at XMLHttpRequest.handleError ( http://localhost:3000/static/js/bundle.js:146504:14)"[[Prototype]]: Error Login.js:50

    GET https://www.googleapis.com/oauth2/v3/userinfo net::ERR_FAILED

Please check on Git i commented the code and the error, please help me in this

On Wed, 22 May 2024 at 11:18, aniketharx10x @.***> wrote:

hello, try this:

const login = useGoogleLogin({ onSuccess: async (tokenResponse) => { try { const response = await axios.get( 'https://www.googleapis.com/oauth2/v3/userinfo', { headers: { Authorization: Bearer ${tokenResponse.access_token} }, } ); console.log(response.data); } catch (err) { console.log(err); } }, });

I got the user details on the console from this code

— Reply to this email directly, view it on GitHub https://github.com/MomenSherif/react-oauth/issues/346#issuecomment-2123913734, or unsubscribe https://github.com/notifications/unsubscribe-auth/BDGEOWWJQMUAQQGRA64RCX3ZDQWTFAVCNFSM6AAAAABHFBPBSKVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDCMRTHEYTGNZTGQ . You are receiving this because you are subscribed to this thread.Message ID: @.***>