google-auth-library-nodejs icon indicating copy to clipboard operation
google-auth-library-nodejs copied to clipboard

How to sign in user and keep them signed in with react login in with google button

Open Philip2809 opened this issue 3 years ago • 0 comments

Hi!

I am trying to make a simple sign in system but I can't seem to find the correct documentation of what to use that is up to date and works as I need it to. I have a react app, where there can be users. I have a sign in page with the sign in with google button and then I have a backend server. I want the user to be able to sign in and then stay signed in. I am not sure if I am thinking about this correct but I get a refresh token, that is saved in the localstorage and then sent with the requests to the server to be checked, but my refresh token expires after one use, how do I get around this, or if there is a better way to do this: how?

My code so far: (server side, sending a code that was generated by the code below multiple gives gives an error)

app.post('/auth', async (req, res) => {
    const { code } = req.body;
    try {
        const r = await client.getToken(code);
        const ticket = await client.verifyIdToken({
            idToken: r.tokens.id_token
        });
        const { given_name, family_name, email } = ticket.getPayload();
        res.status(201);
        res.json({
            email: email,
            förnamn: given_name,
            efternamn: family_name,
        });
    } catch{
        res.status(401);
    }
});

Code that sends

const res = await fetch('http://localhost:5000/auth', {
      method: 'POST',
      body: JSON.stringify({
        code: JSON.parse(loginToken),
      }),
      headers: {
        'Content-Type': 'application/json',
      },
    });

code that generates the code

 <GoogleLogin
              clientId={clientID}
              buttonText="Log in with Google"
              onSuccess={handleLogin}
              onFailure={handleFailure}
              cookiePolicy={'single_host_origin'}
              accessType="offline"
              responseType='code'
            ></GoogleLogin>

Thanks for the help in advance!

Best regards Philip Magyar

Philip2809 avatar Feb 28 '22 20:02 Philip2809