🌸

Auth.jsのv5のGoogle認証をちょっと実装してみた

に公開

はじめに

Auth.jsのv5のGoogle認証を実装してみました。

NextAuth.jsとAuth.js

NextAuth.jsで検索して調べてたらそういえばAuth.jsになったんだってことを思い出しました笑
https://next-auth.js.org/getting-started/example

https://authjs.dev/getting-started/installation

NextAuth.js is becoming Auth.js! 🎉 We're creating Authentication for the Web. Everyone included. You are looking at the NextAuth.js (v4) documentation. For the new documentation go to authjs.dev.

Google CloudでIDとSECRETを取得

実装する前に、Google CloudでAUTH_GOOGLE_IDとAUTH_GOOGLE_SECRETが必要になるので取得しにいきます。
https://console.cloud.google.com/welcome?hl=ja&inv=1&invt=Ab26eA&project=gen-lang-client-0928325109
下記の画像の赤い枠をクリックや入力していってください。








認証済みのリダイレクトUIには、Callback URLを入れます。

http://localhost:3000/api/auth/callback/google(ローカルの場合)

/api/auth/callback/[provider名] を認証後の戻り先として使うと決まっているのはここに書いてあります。
https://authjs.dev/getting-started/providers/salesforce?utm_source=chatgpt.com
ここでIDとシークレットをコピーしておきます。

これで完成です🎉

インストールとAUTH_SECRET生成

https://authjs.dev/getting-started/installation

こちらでインストールします。まだ安定版ではないので@bataがついています。

$ npm install next-auth@beta

secretを作成します。

$ npx auth secret

AUTH_SECRETを作ります。

$ npx auth secret

上記のコマンドを打つと、下記の表示が出てきます。

Need to install the following packages:
auth@1.2.3
Ok to proceed? (y)

➕ Added `AUTH_SECRET` to /Users/mii/Documents/Study/Go/todo/next/.env.local.

.env.localにAUTH_SECRETができます。

AUTH_SECRET="〜〜〜" # Added by `npx auth`. Read more: https://cli.authjs.dev

実装

ツリーはこんな感じです。

こちらがベースとなるコードです。

next/auth.ts
import NextAuth from "next-auth"
 
export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [],
})
next/src/app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth" 
export const { GET, POST } = handlers
next/middleware.ts
export { auth as middleware } from "@/auth"

ここにGoogle Providerの実装を追加してきます。
https://authjs.dev/getting-started/authentication/oauth

OAuthの画面でGoogleのボタンを押すと実装方法が書いてあります。

ドキュメントにはこのように記載してあるので、記載します。

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

export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [
    Google({
      clientId: process.env.AUTH_GOOGLE_ID!,//追加
      clientSecret: process.env.AUTH_GOOGLE_SECRET!,//追加
    }),
  ],
});

Vercelでデプロイ

今回は、すでにデプロイしているアプリに追加で認証をデプロイします。
先ほど作ったGoogle Cloudの認証ずみリダイレクトUIに本番環境のURLを入れてください。

Vercelのデプロイを押下し

Redeployを押下します。

これで反映されます🎉

さいごに

サインインとアウトは別の記事に書いていきます!

Discussion