🎍

Auth0 + Next.js 12, ユーザー認証

2021/12/28に公開

概要:

Auth0 ユーザー認証 + next.jsの例になります。


構成

  • next.js 12
  • Auth0
  • node 16

参考のコード

https://github.com/kuc-arc-f/nextjs12_3


準備

  • next.js12 を準備(空の状態)

  • Auth0に、アカウント作成しておきます

  • application の作成

ダッシュボード> application > create application おす

  • Regular web application 選択

  • next.jsを選択、次に設定画面が表示されたので。
    説明に従って、進めます・

  • 設定など

Domain
Client ID
Client Secret を、メモしておきます

npm install @auth0/nextjs-auth0
  • .env の設定、画面に表示されている。設定値をコピー
AUTH0_SECRET='use [openssl rand -hex 32] to generate a 32 bytes value'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL=' '
AUTH0_CLIENT_ID=' '
AUTH0_CLIENT_SECRET=' '

AUTH0_SECRETは、opensslコマンドで作成してコードを、設定


pages/api/auth/[...auth0].ts

[...auth0].ts
import { handleAuth } from '@auth0/nextjs-auth0';

export default handleAuth();
  • pages/_app.ts
_app.ts
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0';

export default function App({ Component, pageProps }) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  );
}

  • src/pages/index.tsx
index.tsx
import type { NextPage } from 'next'
import Head from 'next/head'
import styles from '../styles/Home.module.css'

const Home: NextPage = () => {
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>
          Welcome to <a href="https://nextjs.org">Next.js!</a>
        </h1>
      </main>
      <hr />
      <a href="/api/auth/login">Login</a>
      <hr />
      <a href="/api/auth/logout">Logout</a>
      <hr />
      <a href="/profile">profile</a>
      <hr />

    </div>
  )
}

export default Home

  • Loginおすと、ホスティングされて。ログイン画面でます
  • 初回は、sign upリンク押して、ユーザー追加後ログイン


  • profile.tsx

ログインデータの表示

profile.tsx
import React from 'react';
import { useUser } from '@auth0/nextjs-auth0';

export default function Profile() {
  const { user, error, isLoading } = useUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;

  if(typeof user === 'undefined'){
    console.log("not, Login");
  }else{
    console.log(user);
    console.log("sub=", user.sub);
  }
  
  return (
    user && (
      <div>
        <img src={user.picture} alt={user.name} />
        <h2>{user.name}</h2>
        <p>{user.email}</p>
      </div>
    )
  );
}

....

Discussion