Hono + Google Auth

Hello I am new to this. I want to implement login using google account feature in a personal project. I am using HONO for the backend. Is there a way to do so?

tldr; use Gerar código HTML  |  Authentication  |  Google for Developers and validate the credential response on backend using jose jwt verify

we get a token which is id_token sent from client, after successful google sign in, credential response is given, which is base64 of the jwt, it is generally safe to send it over https to the server, but important to verify the signature in backend, the public key is rotated by google, so although possible to keep it cached in local kv, but has to be fetched from their endpoint in case it expires, the jwt also gets expired, which we can get new by asking google’s oauth endpoint with refresh token, the jwt can be decoded to get the payload which consists of profile info

Hope this helps

interface Env {
  GOOGLE_CLIENT_ID: string;
  GOOGLE_CLIENT_SECRET: string;
  GOOGLE_REDIRECT_URI: string;
}
// Route to start the OAuth flow
app.get('/auth', async (c) => {
  const env: Env = c.env;
  const GOOGLE_AUTH_ENDPOINT = 'https://accounts.google.com/o/oauth2/v2/auth';
  const responseType = 'code';
  const scope = encodeURIComponent('https://www.googleapis.com/auth/userinfo.email');
  const accessType = 'offline'; // For getting a refresh token

  // Construct the authorization URL manually
  const authUrl = `${GOOGLE_AUTH_ENDPOINT}?response_type=${responseType}&client_id=${encodeURIComponent(env.GOOGLE_CLIENT_ID)}&redirect_uri=${encodeURIComponent(env.GOOGLE_REDIRECT_URI)}&scope=${scope}&access_type=${accessType}`;
  return c.redirect(authUrl);
});

// OAuth callback route
app.get('/oauth2callback', async (c) => {
  const env: Env = c.env;
  const url = new URL(c.req.url);
  const code = url.searchParams.get('code');

  if (!code) {
    return c.text('Authorization code not found', 400);
  }

  const GOOGLE_TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';

  const tokenResponse = await fetch(GOOGLE_TOKEN_ENDPOINT, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
      code: code,
      client_id: env.GOOGLE_CLIENT_ID,
      client_secret: env.GOOGLE_CLIENT_SECRET,
      redirect_uri: env.GOOGLE_REDIRECT_URI,
      grant_type: 'authorization_code',
    }),
  });

  const tokenData = await tokenResponse.json();

  if (!tokenData.access_token) {
    return c.text('Failed to obtain access token', 400);
  }
  return c.text('User account created successfully.');

});