I want to do authorization via Google using next-auth

663 views Asked by At

I want to do authorization via Google using next-auth. But I can't do it, tell me why. In the usual authorization, I made a secret word and password, hashed it all, connected the signature, transmitted it to the server, checked it on the server with the database, and if there was a match, the user received cookies.But here I don't understand a lot

.env

 GOOGLE_CLIENT_ID=********************************
 GOOGLE_CLIENT_SECRET=********************************
 NEXTAUTH_URL=http://localhost:3000
 NEXTAUTH_SECRET=********************************

api/auth/[...nextauth].ts

import NextAuth from "next-auth/next";
import GoogleProvider from "next-auth/providers/google";

export default NextAuth({
    providers: [
         GoogleProvider({
             clientId: process.env.GOOGLE_CLIENT_ID,
             clientSecret: process.env.GOOGLE_CLIENT_SECRET
        })
    ],
      pages: {
        signIn: "/",
       },
    })

index.tsx

import { useSession, signOut,signIn } from "next-auth/react";

    const { data: session } = useSession()
        if (session) {
            return (
              <>
         Signed in as {session.user.email} <br />
                <button onClick={() => signOut()}>Sign out</button>
              </>
            )
          }
          return  (
            <>
         Not signed in <br />
              <button onClick={() => signIn ()}>Sign in</button>
            </>
          )

I just have my redirect to the main page and the request status is 302, but there is no session data in the request itsel, for just a redirect just happens. I tried to pass my api/auth/[...nextauth].ts

export default NextAuth({
    providers: [
         GoogleProvider({
             clientId: process.env.GOOGLE_CLIENT_ID,
             clientSecret: process.env.GOOGLE_CLIENT_SECRET
        })
    ],
    })
],
callback:{
  async session({session,token}) {
     session.user.tag=session.user.name
     .split(" ")
     .join("")
     .toLocaleLowerCase();
     session.user.uid=token.sub;
      return session
  },
},
  secret:process.env.JWT_SECRET,
});

400 error redirect_uri does not match the Callback URL specified during application registration But not result

1

There are 1 answers

0
abelSolomon On

I was having the same problems what worked for me was instead of using signIn() i added signIn("google") to the button tag and if you are using multiple authentication provider you use signIn(undefined) and you also can specify the callbackUrl like this signIn("google", { callbackUrl: "/" }) ( don't forget to change the url path to the page you want ) hope this helps