Kurs Next.js · Moduł 7: Uwierzytelnianie i autoryzacja

Implementacja NextAuth.js / Auth.js

16 min czytania ·
W tej lekcji14

NextAuth.js (obecnie znany również jako Auth.js) to kompleksowe rozwiązanie do uwierzytelniania w aplikacjach Next.js. Zapewnia gotową infrastrukturę do zarządzania sesjami, tokenami, logowaniem, rejestracją i integracją z zewnętrznymi dostawcami uwierzytelniania. W tym module zajmiemy się szczegółową implementacją tego narzędzia w aplikacjach Next.js.

Dlaczego warto użyć NextAuth.js?

NextAuth.js oferuje wiele korzyści:

  1. Gotowe rozwiązanie - nie trzeba implementować uwierzytelniania od podstaw
  2. Wsparcie dla różnych dostawców - oferuje integrację z ponad 50 dostawcami uwierzytelniania
  3. Bezpieczeństwo - implementuje najlepsze praktyki bezpieczeństwa
  4. Zarządzanie sesjami - obsługuje sesje po stronie serwera i klienta
  5. Elastyczność - można go dostosować do konkretnych potrzeb aplikacji
  6. Wsparcie dla App Router - działa z nową architekturą Next.js
  7. Rozszerzona typizacja TypeScript - oferuje pełne wsparcie dla typów

Instalacja i podstawowa konfiguracja

Zacznijmy od instalacji NextAuth.js:

npm install next-auth@latest
# lub
yarn add next-auth@latest
# lub
pnpm add next-auth@latest

Konfiguracja podstawowa dla App Router

Aby skonfigurować NextAuth.js w architekturze App Router, musimy utworzyć plik do obsługi Route API dla uwierzytelniania:

// app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";

export const authOptions = {
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID!,
      clientSecret: process.env.GITHUB_SECRET!
    })
  ],
  // Dodatkowe opcje konfiguracyjne...
};

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

Ten plik tworzy dynamiczną trasę API, która obsługuje wszystkie niezbędne endpointy do uwierzytelniania.

Dodanie komponentu SessionProvider

Aby umożliwić korzystanie z hooka useSession w komponentach po stronie klienta, musimy dodać SessionProvider do naszej aplikacji. Najlepiej zrobić to w pliku Provider lub bezpośrednio w głównym layoucie:

// app/providers.tsx
'use client';

import { SessionProvider } from "next-auth/react";
import { ReactNode } from "react";

export function Providers({ children }: { children: ReactNode }) {
  return <SessionProvider>{children}</SessionProvider>;
}

// app/layout.tsx
import { Providers } from "./providers";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

Konfiguracja zmiennych środowiskowych

NextAuth.js wymaga kilku zmiennych środowiskowych. Utwórz lub zaktualizuj plik .env.local w głównym katalogu projektu:

# Podstawowa konfiguracja dla NextAuth.js
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=twój_tajny_klucz_do_szyfrowania_jwt

# Dane uwierzytelniania GitHub (przykład)
GITHUB_ID=twoje_github_client_id
GITHUB_SECRET=twoje_github_client_secret

W środowisku produkcyjnym:

  • NEXTAUTH_URL powinien być pełnym adresem URL Twojej aplikacji
  • NEXTAUTH_SECRET powinien być długim, losowym ciągiem znaków. Możesz go wygenerować za pomocą komendy openssl rand -base64 32.

Konfiguracja różnych dostawców uwierzytelniania

NextAuth.js obsługuje wiele dostawców uwierzytelniania. Przyjrzyjmy się, jak skonfigurować kilka popularnych:

1. Uwierzytelnianie z GitHub

import GithubProvider from "next-auth/providers/github";

export const authOptions = {
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID!,
      clientSecret: process.env.GITHUB_SECRET!,
      // Opcjonalne parametry
      scope: "read:user user:email", // Określa zakres dostępu
      profile(profile) {
        // Dostosowanie profilu użytkownika
        return {
          id: profile.id.toString(),
          name: profile.name || profile.login,
          email: profile.email,
          image: profile.avatar_url,
          // Dodatkowe pola
          username: profile.login,
        };
      },
    }),
  ],
  // Pozostałe opcje konfiguracyjne...
};

2. Uwierzytelnianie z Google

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

export const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
      // Opcjonalne parametry
      authorization: {
        params: Promise<{
          prompt: "consent",
          access_type: "offline",
          response_type: "code"
        }>
      }
    }),
  ],
  // Pozostałe opcje konfiguracyjne...
};

3. Uwierzytelnianie z danych uwierzytelniających (email/hasło)

import CredentialsProvider from "next-auth/providers/credentials";
import { compare } from "bcrypt";
import { prisma } from "@/lib/prisma"; // Zakładamy, że masz skonfigurowaną instancję Prisma

export const authOptions = {
  providers: [
    CredentialsProvider({
      // Nazwa wyświetlana na stronie logowania
      name: "Credentials",
      // Konfiguracja pól formularza logowania
      credentials: {
        email: { label: "Email", type: "email" },
        password: { label: "Hasło", type: "password" }
      },
      async authorize(credentials) {
        // Sprawdź, czy credentials istnieją
        if (!credentials?.email || !credentials?.password) {
          return null;
        }

        try {
          // Znajdź użytkownika w bazie danych
          const user = await prisma.user.findUnique({
            where: { email: credentials.email },
          });

          if (!user || !user.password) {
            return null;
          }

          // Sprawdź, czy hasło jest poprawne
          const isPasswordValid = await compare(
            credentials.password,
            user.password
          );

          if (!isPasswordValid) {
            return null;
          }

          // Zwróć obiekt użytkownika (bez hasła)
          return {
            id: user.id,
            name: user.name,
            email: user.email,
            role: user.role,
            // Inne pola, które chcesz uwzględnić
          };
        } catch (error) {
          console.error("Authentication error:", error);
          return null;
        }
      },
    }),
  ],
  // Pozostałe opcje konfiguracyjne...
};

4. Uwierzytelnianie z wielu dostawców

Możesz połączyć wielu dostawców uwierzytelniania:

export const authOptions = {
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID!,
      clientSecret: process.env.GITHUB_SECRET!,
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
    CredentialsProvider({
      // Konfiguracja...
      async authorize(credentials) {
        // Logika uwierzytelniania...
      },
    }),
    // Możesz dodać więcej dostawców...
  ],
  // Pozostałe opcje konfiguracyjne...
};

Konfiguracja opcji sesji i JWT

NextAuth.js oferuje różne strategie sesji:

export const authOptions = {
  // Konfiguracja dostawców...

  session: {
    // Wybierz strategię: 'jwt' lub 'database'
    strategy: 'jwt',

    // Maksymalny czas życia sesji (w sekundach)
    maxAge: 30 * 24 * 60 * 60, // 30 dni

    // Aktualizacja sesji przy każdym żądaniu, wydłużając jej ważność
    updateAge: 24 * 60 * 60, // 24 godziny
  },

  // Konfiguracja JWT (tylko dla strategii 'jwt')
  jwt: {
    // Tajny klucz używany do podpisywania tokenów JWT
    // Domyślnie używa NEXTAUTH_SECRET
    secret: process.env.JWT_SECRET,

    // Możesz dostosować enkoder/dekoder JWT
    // encode: async ({ secret, token, maxAge }) => {},
    // decode: async ({ secret, token }) => {},
  },
};

Niestandardowe strony uwierzytelniania

Domyślnie NextAuth.js dostarcza proste strony do logowania, ale możesz je zastąpić własnymi:

export const authOptions = {
  // Konfiguracja dostawców...

  pages: {
    signIn: '/auth/login',
    signOut: '/auth/logout',
    error: '/auth/error', // Błąd uwierzytelniania (np. niewłaściwe dane)
    verifyRequest: '/auth/verify-request', // Używane dla Magic Links
    newUser: '/auth/new-user' // Strona po pierwszej rejestracji
  },
};

Następnie musisz utworzyć te strony w swojej aplikacji. Oto przykład strony logowania:

// app/auth/login/page.tsx
'use client';

import { signIn, useSession } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useState, useEffect } from 'react';

export default function LoginPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get('callbackUrl') || '/dashboard';
  const { status } = useSession();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  // Przekieruj zalogowanego użytkownika
  useEffect(() => {
    if (status === 'authenticated') {
      router.push(callbackUrl);
    }
  }, [status, router, callbackUrl]);

  // Obsługa logowania z GitHub
  const handleGitHubSignIn = () => {
    setIsLoading(true);
    signIn('github', { callbackUrl });
  };

  // Obsługa logowania z Google
  const handleGoogleSignIn = () => {
    setIsLoading(true);
    signIn('google', { callbackUrl });
  };

  // Obsługa logowania z danymi uwierzytelniającymi
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError('');

    try {
      const result = await signIn('credentials', {
        redirect: false,
        email,
        password,
      });

      if (result?.error) {
        setError('Nieprawidłowy email lub hasło');
        setIsLoading(false);
      } else {
        router.push(callbackUrl);
      }
    } catch (error) {
      setError('Wystąpił błąd podczas logowania');
      setIsLoading(false);
    }
  };

  if (status === 'loading') {
    return <div>Ładowanie...</div>;
  }

  return (
    <div className="max-w-md mx-auto mt-10 p-6 bg-white rounded-lg shadow-md">
      <h1 className="text-2xl font-bold mb-6 text-center">Zaloguj się</h1>

      {error && (
        <div className="mb-4 p-3 bg-red-100 text-red-700 rounded">
          {error}
        </div>
      )}

      <div className="space-y-4 mb-6">
        <button
          type="button"
          onClick={handleGitHubSignIn}
          disabled={isLoading}
          className="w-full flex items-center justify-center gap-2 p-2 border border-gray-300 rounded-md hover:bg-gray-50"
        >
          <svg width="20" height="20" fill="currentColor" viewBox="0 0 24 24">
            {/* Logo GitHub */}
            <path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z" />
          </svg>
          Kontynuuj z GitHub
        </button>

        <button
          type="button"
          onClick={handleGoogleSignIn}
          disabled={isLoading}
          className="w-full flex items-center justify-center gap-2 p-2 border border-gray-300 rounded-md hover:bg-gray-50"
        >
          <svg width="20" height="20" fill="currentColor" viewBox="0 0 24 24">
            {/* Logo Google */}
            <path d="M12 24C5.385 24 0 18.615 0 12S5.385 0 12 0s12 5.385 12 12-5.385 12-12 12zm0-22.5C6.21 1.5 1.5 6.21 1.5 12S6.21 22.5 12 22.5 22.5 17.79 22.5 12 17.79 1.5 12 1.5zm-5.25 9v3h3v3h3v-3h3v-3h-3v-3h-3v3h-3z" />
          </svg>
          Kontynuuj z Google
        </button>
      </div>

      <div className="relative my-6">
        <div className="absolute inset-0 flex items-center">
          <div className="w-full border-t border-gray-300"></div>
        </div>
        <div className="relative flex justify-center text-sm">
          <span className="px-2 bg-white text-gray-500">
            lub zaloguj się za pomocą emaila
          </span>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label htmlFor="email" className="block text-sm font-medium mb-1">
            Email
          </label>
          <input
            id="email"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            className="w-full px-3 py-2 border border-gray-300 rounded-md"
          />
        </div>

        <div>
          <label htmlFor="password" className="block text-sm font-medium mb-1">
            Hasło
          </label>
          <input
            id="password"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            className="w-full px-3 py-2 border border-gray-300 rounded-md"
          />
        </div>

        <button
          type="submit"
          disabled={isLoading}
          className="w-full bg-blue-500 text-white py-2 px-4 rounded-md hover:bg-blue-600 disabled:opacity-50"
        >
          {isLoading ? 'Logowanie...' : 'Zaloguj się'}
        </button>
      </form>
    </div>
  );
}

Callbacki i zdarzenia

NextAuth.js umożliwia reagowanie na różne zdarzenia w cyklu życia uwierzytelniania poprzez callbacki:

export const authOptions = {
  // Konfiguracja dostawców...

  callbacks: {
    // Wywoływany przy tworzeniu sesji
    async session({ session, token }) {
      // Dodaj dane z tokenu do sesji
      if (token.sub && session.user) {
        session.user.id = token.sub;
      }

      // Dodaj niestandardowe pola, np. rolę użytkownika
      if (token.role && session.user) {
        session.user.role = token.role as string;
      }

      return session;
    },

    // Wywoływany przy tworzeniu JWT
    async jwt({ token, user, account, profile }) {
      // Dodaj dane użytkownika przy pierwszym zalogowaniu
      if (user) {
        token.role = user.role;
        // Inne niestandardowe pola...
      }

      return token;
    },

    // Wywoływany po zalogowaniu
    async signIn({ user, account, profile, email, credentials }) {
      // Sprawdź, czy użytkownik ma dostęp do aplikacji
      return true; // Zwróć false, aby odmówić dostępu
    },

    // Wywoływany podczas przekierowania
    async redirect({ url, baseUrl }) {
      // Zasady przekierowań
      if (url.startsWith(baseUrl)) {
        return url;
      }
      // Domyślnie przekieruj na stronę bazową
      return baseUrl;
    },
  },

  // Zdarzenia
  events: {
    async signIn(message) {
      // Wywołane po zalogowaniu
      console.log('User signed in:', message);
    },
    async signOut(message) {
      // Wywołane po wylogowaniu
      console.log('User signed out:', message);
    },
    async createUser(message) {
      // Wywołane po utworzeniu użytkownika
      console.log('User created:', message);
    },
    async linkAccount(message) {
      // Wywołane po powiązaniu konta
      console.log('Account linked:', message);
    },
    async session(message) {
      // Wywołane po utworzeniu sesji
      console.log('Session created/updated:', message);
    },
  },
};

Rozszerzanie typów dla TypeScript

Jeśli używasz TypeScript, możesz rozszerzyć typy NextAuth.js, aby uwzględnić niestandardowe pola:

// W pliku z rozszerzeniami typów (np. types/next-auth.d.ts)
import 'next-auth';
import 'next-auth/jwt';

declare module 'next-auth' {
  interface Session {
    user: {
      id: string;
      name?: string | null;
      email?: string | null;
      image?: string | null;
      role?: string;
      // Dodaj inne niestandardowe pola...
    };
  }

  interface User {
    id: string;
    name?: string | null;
    email?: string | null;
    image?: string | null;
    role?: string;
    // Dodaj inne niestandardowe pola...
  }
}

declare module 'next-auth/jwt' {
  interface JWT {
    role?: string;
    // Dodaj inne niestandardowe pola...
  }
}

Adaptery bazy danych

Aby używać strategii sesji opartej na bazie danych lub przechowywać konta użytkowników, NextAuth.js oferuje adaptery dla różnych baz danych:

Konfiguracja z Prisma

import { PrismaAdapter } from "@auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export const authOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    // Konfiguracja dostawców...
  ],
  // Pozostałe opcje...
};

Schemat Prisma powinien zawierać odpowiednie modele:

// prisma/schema.prisma
model Account {
  id                String  @id @default(cuid())
  userId            String
  type              String
  provider          String
  providerAccountId String
  refresh_token     String? @db.Text
  access_token      String? @db.Text
  expires_at        Int?
  token_type        String?
  scope             String?
  id_token          String? @db.Text
  session_state     String?

  user User @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@unique([provider, providerAccountId])
}

model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique
  userId       String
  expires      DateTime
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  password      String?
  role          String?   @default("user")
  accounts      Account[]
  sessions      Session[]
}

model VerificationToken {
  identifier String
  token      String   @unique
  expires    DateTime

  @@unique([identifier, token])
}

Inne dostępne adaptery

NextAuth.js oferuje adaptery dla wielu baz danych:

  • Adaptery SQL: PostgreSQL, MySQL, SQLite, SQL Server
  • Adaptery nierelacyjne: MongoDB, DynamoDB
  • ORM/ODM: Prisma, Mongoose, Typeorm, Sequelize, DrizzleORM
  • Inne: Firebase, Supabase, Kysely, Planetscale, Xata

Używanie uwierzytelniania w aplikacji

1. Pobieranie danych sesji po stronie klienta

Po skonfigurowaniu NextAuth.js, możesz używać hooka useSession w komponentach klienckich:

'use client';

import { useSession } from 'next-auth/react';
import { redirect } from 'next/navigation';

export default function Dashboard() {
  const { data: session, status } = useSession({
    required: true,
    onUnauthenticated() {
      redirect('/auth/login?callbackUrl=/dashboard');
    },
  });

  if (status === 'loading') {
    return <div>Ładowanie...</div>;
  }

  return (
    <div>
      <h1>Dashboard</h1>
      <p>Witaj, {session.user.name}!</p>
      <p>Twój email: {session.user.email}</p>
      {session.user.role === 'admin' && (
        <div>
          <h2>Panel administratora</h2>
          {/* Zawartość tylko dla administratorów */}
        </div>
      )}
    </div>
  );
}

2. Pobieranie danych sesji po stronie serwera

W komponentach renderowanych na serwerze, możesz użyć getServerSession:

// app/profile/page.tsx
import { getServerSession } from 'next-auth/next';
import { redirect } from 'next/navigation';
import { authOptions } from '../api/auth/[...nextauth]/route';

export default async function ProfilePage() {
  const session = await getServerSession(authOptions);

  if (!session) {
    redirect('/auth/login?callbackUrl=/profile');
  }

  return (
    <div>
      <h1>Profil</h1>
      <p>Witaj, {session.user.name}!</p>
      <p>Twój email: {session.user.email}</p>
      {/* Reszta zawartości profilu */}
    </div>
  );
}

3. Zarządzanie stanem uwierzytelniania

NextAuth.js dostarcza funkcje do zarządzania stanem uwierzytelniania:

'use client';

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

export function AuthButton() {
  const { data: session } = useSession();

  if (session) {
    return (
      <button
        onClick={() => signOut({ callbackUrl: '/' })}
        className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
      >
        Wyloguj się
      </button>
    );
  }

  return (
    <button
      onClick={() => signIn()}
      className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
    >
      Zaloguj się
    </button>
  );
}

Dostosowanie UI do NextAuth.js

Możemy stworzyć komponent, który renderuje różne elementy interfejsu w zależności od stanu uwierzytelniania:

'use client';

import { useSession } from 'next-auth/react';
import Link from 'next/link';
import { AuthButton } from './AuthButton';

export function Navbar() {
  const { data: session, status } = useSession();
  const isLoading = status === 'loading';

  return (
    <nav className="bg-white shadow-md p-4">
      <div className="container mx-auto flex justify-between items-center">
        <Link href="/" className="text-xl font-bold">
          MojaAplikacja
        </Link>

        <div className="flex items-center space-x-4">
          <Link href="/" className="hover:text-blue-500">
            Strona główna
          </Link>

          {session ? (
            <>
              <Link href="/dashboard" className="hover:text-blue-500">
                Dashboard
              </Link>
              <Link href="/profile" className="hover:text-blue-500">
                Profil
              </Link>
              {session.user.role === 'admin' && (
                <Link href="/admin" className="hover:text-blue-500">
                  Admin
                </Link>
              )}
            </>
          ) : (
            <Link href="/features" className="hover:text-blue-500">
              Funkcje
            </Link>
          )}

          {!isLoading && (
            <div className="flex items-center space-x-2">
              {session && (
                <div className="flex items-center">
                  {session.user.image && (
                    <img
                      src={session.user.image}
                      alt={session.user.name || 'User'}
                      className="w-8 h-8 rounded-full mr-2"
                    />
                  )}
                  <span className="text-sm font-medium">
                    {session.user.name}
                  </span>
                </div>
              )}
              <AuthButton />
            </div>
          )}
        </div>
      </div>
    </nav>
  );
}

Uwierzytelnianie z API Routes

NextAuth.js może być również używany do zabezpieczania endpointów API:

// app/api/protected-data/route.ts
import { getServerSession } from 'next-auth/next';
import { NextResponse } from 'next/server';
import { authOptions } from '../auth/[...nextauth]/route';

export async function GET() {
  const session = await getServerSession(authOptions);

  if (!session) {
    return NextResponse.json(
      { message: 'Nieautoryzowany dostęp' },
      { status: 401 }
    );
  }

  // Sprawdź uprawnienia na podstawie roli (opcjonalnie)
  if (session.user.role !== 'admin') {
    return NextResponse.json(
      { message: 'Brak uprawnień dostępu' },
      { status: 403 }
    );
  }

  // Dane dostępne tylko dla zalogowanych użytkowników (i administratorów, jeśli sprawdzamy role)
  return NextResponse.json({
    message: 'Sukces',
    data: {
      secretContent: 'Te dane są chronione',
      timestamp: new Date().toISOString()
    }
  });
}

Dobre praktyki przy implementacji NextAuth.js

  1. Bezpieczeństwo przede wszystkim

    • Używaj HTTPS w środowisku produkcyjnym
    • Generuj silne NEXTAUTH_SECRET
    • Nigdy nie przechowuj wrażliwych danych w tokenach JWT
  2. Optymalizacja wydajności

    • Wykorzystuj strategie sesji odpowiednie do twoich potrzeb
    • Rozważ używanie strategii JWT dla większej skalowalności
  3. Obsługa błędów

    • Implementuj niestandardowe strony błędów
    • Rejestruj błędy uwierzytelniania do analizy
  4. Doświadczenie użytkownika

    • Projektuj przyjazne formularze logowania
    • Umożliwiaj płynne przełączanie między dostawcami
  5. Testowanie

    • Testuj różne scenariusze uwierzytelniania
    • Sprawdzaj, jak aplikacja reaguje na wygasłe sesje

Zaawansowane scenariusze

1. Uwierzytelnianie wieloetapowe

W niektórych przypadkach możesz chcieć zaimplementować uwierzytelnianie wieloetapowe (np. hasło + kod SMS):

// Zaimplementuj niestandardowy CredentialsProvider
CredentialsProvider({
  name: 'TwoFactor',
  credentials: {
    email: { label: "Email", type: "email" },
    password: { label: "Hasło", type: "password" },
    code: { label: "Kod weryfikacyjny", type: "text" }
  },
  async authorize(credentials) {
    if (!credentials?.email || !credentials?.password) {
      return null;
    }

    // Pierwszy etap: sprawdź hasło
    const user = await prisma.user.findUnique({
      where: { email: credentials.email }
    });

    if (!user || !await compare(credentials.password, user.password)) {
      return null;
    }

    // Drugi etap: sprawdź kod weryfikacyjny
    if (credentials.code) {
      const isValidCode = await verifyTwoFactorCode(user.id, credentials.code);

      if (!isValidCode) {
        return null;
      }
    } else {
      // Jeśli kod nie został podany, a jest wymagany
      if (user.twoFactorEnabled) {
        // Wysyłanie kodu na email/telefon
        await sendTwoFactorCode(user);

        // Zwróć specjalny obiekt, aby App Router wiedział, że potrzebujemy kodu
        throw new Error('TwoFactorRequired');
      }
    }

    // Uwierzytelnienie zakończone sukcesem
    return {
      id: user.id,
      email: user.email,
      name: user.name,
      role: user.role
    };
  }
})

2. Implementacja własnej logiki rejestracji

// app/api/register/route.ts
import { NextResponse } from 'next/server';
import { hash } from 'bcrypt';
import { prisma } from '@/lib/prisma';
import { z } from 'zod';

// Schemat walidacji
const userSchema = z.object({
  name: z.string().min(2, 'Imię musi mieć co najmniej 2 znaki'),
  email: z.string().email('Nieprawidłowy adres email'),
  password: z.string().min(8, 'Hasło musi mieć co najmniej 8 znaków')
});

export async function POST(request: Request) {
  try {
    const body = await request.json();

    // Walidacja danych
    const result = userSchema.safeParse(body);

    if (!result.success) {
      return NextResponse.json(
        { message: result.error.errors[0].message },
        { status: 400 }
      );
    }

    const { name, email, password } = result.data;

    // Sprawdź, czy użytkownik już istnieje
    const existingUser = await prisma.user.findUnique({
      where: { email }
    });

    if (existingUser) {
      return NextResponse.json(
        { message: 'Użytkownik o podanym adresie email już istnieje' },
        { status: 409 }
      );
    }

    // Haszowanie hasła
    const hashedPassword = await hash(password, 10);

    // Utworzenie nowego użytkownika
    const user = await prisma.user.create({
      data: {
        name,
        email,
        password: hashedPassword,
        role: 'user' // Domyślna rola
      }
    });

    // Nie zwracaj hasła w odpowiedzi
    const { password: _, ...userWithoutPassword } = user;

    return NextResponse.json(
      { message: 'Rejestracja zakończona pomyślnie', user: userWithoutPassword },
      { status: 201 }
    );
  } catch (error) {
    console.error('Registration error:', error);
    return NextResponse.json(
      { message: 'Wystąpił błąd serwera' },
      { status: 500 }
    );
  }
}

Podsumowanie

NextAuth.js (Auth.js) to wszechstronne narzędzie do implementacji uwierzytelniania w aplikacjach Next.js. Oferuje:

  1. Elastyczność - obsługuje wiele strategii uwierzytelniania
  2. Integrację - łatwo integruje się z różnymi dostawcami
  3. Bezpieczeństwo - implementuje najlepsze praktyki zabezpieczeń
  4. Skalowalność - działa z różnymi bazami danych i architekturami
  5. Rozszerzalność - można go dostosować do specyficznych potrzeb

Dzięki NextAuth.js możesz szybko zaimplementować kompletny system uwierzytelniania w swojej aplikacji Next.js, oszczędzając czas i minimalizując ryzyko błędów związanych z bezpieczeństwem.

W kolejnych modułach omówimy bardziej zaawansowane aspekty uwierzytelniania, w tym strategie uwierzytelniania, zarządzanie sesjami i tokenami, oraz implementację ról i uprawnień.

Kod do tej lekcji: App.tsx
import React, { useState } from 'react';

// Demo: NextAuth.js / Auth.js - konfiguracja i providery
interface AuthConfig {
  provider: string;
  callbackUrl: string;
  strategy: 'jwt' | 'database';
  maxAge: number;
}

const defaultProviders: AuthConfig[] = [
  { provider: 'credentials', callbackUrl: '/dashboard', strategy: 'jwt', maxAge: 3600 },
  { provider: 'google', callbackUrl: '/dashboard', strategy: 'jwt', maxAge: 86400 },
  { provider: 'github', callbackUrl: '/dashboard', strategy: 'database', maxAge: 604800 },
];

function AuthConfigBuilder() {
  const [configs, setConfigs] = useState<AuthConfig[]>(defaultProviders);
  const [newProvider, setNewProvider] = useState('');
  const [strategy, setStrategy] = useState<'jwt' | 'database'>('jwt');
  const [showCode, setShowCode] = useState(false);

  const addProvider = () => {
    if (!newProvider.trim()) return;
    setConfigs(prev => [...prev, {
      provider: newProvider.trim(),
      callbackUrl: '/dashboard',
      strategy,
      maxAge: strategy === 'jwt' ? 3600 : 86400,
    }]);
    setNewProvider('');
  };

  const removeProvider = (index: number) => {
    setConfigs(prev => prev.filter((_, i) => i !== index));
  };

  // Słowa kluczowe ze zmiennych: podgląd edytora usuwa z kodu linie import/export, także te w tekście szablonu
  const kw = { imp: 'import', exp: 'export' };
  const generatedCode = `// app/api/auth/[...nextauth]/route.ts
${kw.imp} NextAuth from 'next-auth';
${configs.map(c => {
  if (c.provider === 'credentials') return kw.imp + " CredentialsProvider from 'next-auth/providers/credentials';";
  return kw.imp + " " + c.provider.charAt(0).toUpperCase() + c.provider.slice(1) + "Provider from 'next-auth/providers/" + c.provider + "';";
}).join('\n')}

${kw.exp} const authOptions = {
  providers: [
${configs.map(c => "    // " + c.provider + " provider\n    // strategy: " + c.strategy).join(',\n')}
  ],
  session: {
    strategy: '${configs[0]?.strategy || 'jwt'}',
    maxAge: ${configs[0]?.maxAge || 3600},
  },
  callbacks: {
    async jwt({ token, user }) {
      if (user) token.role = user.role;
      return token;
    },
    async session({ session, token }) {
      session.user.role = token.role;
      return session;
    },
  },
};`;

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#e0e0e0', fontFamily: 'system-ui' }}>
      <h1 style={{ color: '#64ffda', marginBottom: '8px' }}>NextAuth.js / Auth.js Configuration</h1>
      <p style={{ color: '#8892b0', marginBottom: '24px' }}>Interaktywny konfigurator NextAuth.js - dodawaj providery i generuj kod</p>

      <div style={{ display: 'flex', gap: '12px', marginBottom: '24px', flexWrap: 'wrap' }}>
        <input
          value={newProvider}
          onChange={e => setNewProvider(e.target.value)}
          placeholder="Nazwa providera (np. discord)"
          style={{ padding: '8px 12px', borderRadius: '6px', border: '1px solid #333', background: '#1a1a2e', color: '#fff', flex: 1, minWidth: '200px' }}
        />
        <select
          value={strategy}
          onChange={e => setStrategy(e.target.value as 'jwt' | 'database')}
          style={{ padding: '8px 12px', borderRadius: '6px', border: '1px solid #333', background: '#1a1a2e', color: '#fff' }}
        >
          <option value="jwt">JWT Strategy</option>
          <option value="database">Database Strategy</option>
        </select>
        <button onClick={addProvider} style={{ padding: '8px 16px', borderRadius: '6px', background: '#64ffda', color: '#0f0f23', border: 'none', cursor: 'pointer', fontWeight: 'bold' }}>
          + Dodaj Provider
        </button>
      </div>

      <div style={{ display: 'grid', gap: '12px', marginBottom: '24px' }}>
        {configs.map((config, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px', background: '#1a1a2e', borderRadius: '8px', border: '1px solid #333' }}>
            <div>
              <strong style={{ color: '#64ffda' }}>{config.provider}</strong>
              <span style={{ color: '#8892b0', marginLeft: '12px', fontSize: '14px' }}>
                Strategy: {config.strategy} | MaxAge: {config.maxAge}s
              </span>
            </div>
            <button onClick={() => removeProvider(i)} style={{ background: '#ef4444', color: '#fff', border: 'none', borderRadius: '4px', padding: '4px 8px', cursor: 'pointer' }}>
              Usun
            </button>
          </div>
        ))}
      </div>

      <button
        onClick={() => setShowCode(!showCode)}
        style={{ padding: '10px 20px', borderRadius: '6px', background: showCode ? '#333' : '#7c3aed', color: '#fff', border: 'none', cursor: 'pointer', marginBottom: '16px' }}
      >
        {showCode ? 'Ukryj kod' : 'Wygeneruj kod konfiguracji'}
      </button>

      {showCode && (
        <pre style={{ background: '#1a1a2e', padding: '16px', borderRadius: '8px', overflow: 'auto', fontSize: '13px', lineHeight: 1.5, border: '1px solid #333' }}>
          <code style={{ color: '#e0e0e0' }}>{generatedCode}</code>
        </pre>
      )}
    </div>
  );
}

export default AuthConfigBuilder;

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Authentication oznacza:

  2. 2. Authorization oznacza:

Zadania praktyczne w grze

  • Edytor kodu

    Zbuduj interfejs z chronionymi sekcjami wymagającymi logowania

  • Układanie w pionie

    Ułóż elementy w prawidłowej kolejności: import 'server-only' → export async → fu

  • Klikanie w kolejności

    Ułóż elementy w prawidłowej kolejności: import → NextAuth → from

  • Edytor kodu

    Stwórz komponent logowania z autentykacją JWT

  1. PytanieAuthentication oznacza:
  2. PytanieAuthorization oznacza:
  3. Zadanie z kodemPraktyka: Chronione sekcje z logowaniem
  4. Ułóż w kolejnościKolejność: import 'server-only' → export async → ...
  5. Kliknij w kolejnościKolejność: import → NextAuth → from
  6. Zadanie z kodemPraktyka: Logowanie z JWT

Przydatne artykuły