Auth.js: egen OIDC-leverantör med komplett Next.js-exempel

Du behöver tre värden från utvecklarkonsolen: klient-id:t, klienthemligheten (bara webbserverappar) och den omdirigerings-URI du registrerade. Resten finns i discovery-dokumentet på https://identity.dazr.eu/.well-known/openid-configuration.

Auth.js / NextAuth

Auth.js (NextAuth.js v5) tar ett anpassat OpenID Connect-providerobjekt. Registrera en webbserverapp, ange AUTH_SECRET, AUTH_DAZR_ID och AUTH_DAZR_SECRET och använd den här callback-URL:en som omdirigerings-URI: https://app.example.eu/api/auth/callback/dazr.

// auth.ts
import NextAuth from "next-auth"

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    {
      id: "dazr",
      name: "Dazr Identity",
      type: "oidc",
      issuer: "https://identity.dazr.eu",
      clientId: process.env.AUTH_DAZR_ID,
      clientSecret: process.env.AUTH_DAZR_SECRET,
      authorization: { params: { scope: "openid profile email" } },
      checks: ["pkce", "state", "nonce"],
      client: { id_token_signed_response_alg: "ES256" },
    },
  ],
})

NextAuth.js v4 använder samma idé med type: "oauth" och discovery-URL:en:

// pages/api/auth/[...nextauth].ts (NextAuth.js v4), in providers: [ ... ]
{
  id: "dazr",
  name: "Dazr Identity",
  type: "oauth",
  wellKnown: "https://identity.dazr.eu/.well-known/openid-configuration",
  clientId: process.env.DAZR_CLIENT_ID,
  clientSecret: process.env.DAZR_CLIENT_SECRET,
  authorization: { params: { scope: "openid profile email" } },
  idToken: true,
  checks: ["pkce", "state"],
  client: { id_token_signed_response_alg: "ES256" },
  profile(profile) {
    return { id: profile.sub, name: profile.name ?? null, email: profile.email }
  },
}

Next.js App Router

Med filen auth.ts ovan lägger du till route-hanteraren och en inloggningsknapp som kör en server action.

// app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth"
export const { GET, POST } = handlers

// app/page.tsx
import { auth, signIn, signOut } from "@/auth"

export default async function Page() {
  const session = await auth()
  if (session?.user) {
    return (
      <form action={async () => { "use server"; await signOut() }}>
        <p>Signed in as {session.user.email}</p>
        <button type="submit">Sign out</button>
      </form>
    )
  }
  return (
    <form action={async () => { "use server"; await signIn("dazr") }}>
      <button type="submit" className="dazr-signin">Sign in with Dazr Identity</button>
    </form>
  )
}

Utforma knappen som visas under Knappen. I callbacks är Dazrs sub lika med account.providerAccountId.

Mer för utvecklare