Tutorial 10~25 MinutenFortgeschritten

Authentifizierung

Implementiere JWT, OAuth2 und Multi-Factor Authentication in Velisch.

Was du lernen wirst

  • JWT-Token erstellen und validieren
  • OAuth2 und OpenID Connect
  • Multi-Factor Authentication
1

JWT Integration

Die Standardbibliothek enthält native JWT-Unterstützung für Token-basierte Authentifizierung.

import { jwt } from "std:auth";

// Login und Token erstellen
@POST("/api/login")
fn login(email: string, password: string): LoginResponse {
    let user = db.findBy(User, "email", email);
    
    if (!crypto.argon2Verify(password, user.passwordHash)) {
        throw HttpError(401, "Ungültige Anmeldedaten");
    }
    
    let token = jwt.sign({
        sub: user.id,
        role: user.role,
        exp: now() + "7d",
    }, env.JWT_SECRET);
    
    return LoginResponse { token, user };
}

// Token validieren
@Auth
@GET("/api/profile")
fn getProfile(): User {
    // currentUser() extrahiert User aus validiertem Token
    return currentUser();
}
2

OAuth2 & OIDC

Moderne Authentifizierung mit OAuth2 und OpenID Connect:

// OAuth2-geschützter Endpunkt
@OAuth2
@GET("/api/profile")
fn getOAuthProfile(): User {
    return currentUser();
}

// OpenID Connect
@OIDC
@GET("/api/userinfo")
fn getUserInfo(): UserInfo {
    return fetchUserInfo();
}

// Multi-Factor Authentication
@MFA
@POST("/api/sensitive-action")
fn performSensitiveAction(): ActionResult {
    return executeAction();
}

// Vault Integration für Secrets
@VaultSecret("secret/data/api", "api_key")
struct ApiConfig {
    apiKey: string,
}

Zusammenfassung

Was du gelernt hast:

  • JWT mit std:auth
  • OAuth2 und OIDC Decorators
  • MFA-Integration

Nächste Schritte:

  • Datenbank-Integration