最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

next.js - Next Auth Started Configuration (Google provider) - Stack Overflow

programmeradmin4浏览0评论

Initial configuration file for NextAuth, includes the use case for the Google provider. This is the configuration that worked for the implementation of next auth, it is recommended to export it to use it in [...nextauth].

NextAuth Configuration for Authentication with Google and Credentials Providers In this implementation, we configure NextAuth for handling user authentication. This setup supports both CredentialsProvider (for email/password authentication) and GoogleProvider (for OAuth-based authentication with Google). It uses Prisma as the database client and bcrypt for password hashing and comparison.

Overview:

  • CredentialsProvider: Authenticates users based on email and password.
  • GoogleProvider: Authenticates users via Google OAuth.
  • JWT and Session Management: Generates and manages JWT tokens and sessions.
import { NextAuthOptions, Session, User } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google";
import db from "@/lib/prisma";
import bcrypt from "bcrypt";
import { JWT } from "next-auth/jwt";

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        email: { label: "Email", type: "text", placeholder: "" },
        password: { label: "Password", type: "password", placeholder: "" },
        //Your credentials
      },
      async authorize(credentials: Credentials | undefined) {

        if (!credentials?.email || !credentials?.password) {
          throw new Error("null mail and pass");
        }

        //Strategy of search
        const userFound = await db.user.findUnique({
          where: {
            mail: credentials.email,
          },
        });

        if (!userFound) throw new Error("Not found");

        if (!userFound.password) {
          throw new Error("Not password");
        }

        //For validated password
        const matchPassword = await bcryptpare(credentials.password, userFound.password);

        if (!matchPassword) throw new Error("Not match");

        // Here you return the user info
        return {
          //User info
        };
      },
    }),
    
    //If you need OAuth
    GoogleProvider({
      clientId: //Your client id,
      clientSecret: //Your client secret,

      authorization: {
        params: {
          scope: "openid email profile" //Data response
        }
      }
    })
  ],
  callbacks: {
    async signIn({ user, account }) {
      if (account?.provider === "google") {
        try { 
          //Search strategy for Google Provider
          let existingUser = await db.user.findUnique({
            where: { mail: user.email! }
          });
    
          if (!existingUser) {
            existingUser = await db.user.create({
              data: {
                //Data user after create
              }
            });
          }
          user.id = existingUser.id;
    
          return true;
        } catch (error) {
          console.error("Error in Google Sign-In:", error);
          return false;
        }
      }
      return true;
    },

    //Token generate
    async jwt({ token, user, account }) {
      if (user) {
        //Token params for user
      }
    
      //For Google provider
      if (account?.provider === "google") {
        const existingUser = await db.user.findUnique({
          where: { mail: token.email! } //check existing on db
        });
    
        if (existingUser) {
          //Data user for token
        }
      }
    
      return token;
    }

  },
  pages: {
    signIn: //Your login page,
  },
  session: {
    // Duration of session
    maxAge: 60 * 60, // 1h for example
    // Update actual session
    updateAge: 60 * 60, // 1h for example
  },
  jwt: {
    secret: //Your secret key,
  }
};

Don't forget to wrap the application with the Session Provider.

'use client';

import { SessionProvider } from 'next-auth/react';
import { Session } from 'next-auth';

interface SessionProviderClientComponentProps {
  children: React.ReactNode;
  session: Session | null;
}

export default function SessionProviderClientComponent({
  children,
  session,
}: SessionProviderClientComponentProps) {
  return <SessionProvider session={session}>{children}</SessionProvider>;
}

My [...nextauth] file:

import NextAuth from "next-auth";
import { authOptions } from "@/lib/AuthOption";

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

Notes: Credentials Provider: This handles authentication using a traditional email/password mechanism. It ensures that the password is validated using bcrypt. Google Provider: The OAuth flow with Google allows users to sign in using their Google account. If the user is not found in the database, a new user is created. Session Management: The session duration is set to 1 hour, with regular updates. JWT tokens are used for maintaining user authentication state. Security: Always keep your JWT secret safe and never expose it in client-side code. This setup should work for most use cases involving both traditional credentials-based login and OAuth authentication through Google.

发布评论

评论列表(0)

  1. 暂无评论