@zigatech/keycloak-auth
Version:
Keycloak authorization library for NestJS. Works out of the box.
44 lines (43 loc) • 1.74 kB
JavaScript
import { ForbiddenException, Logger } from "@nestjs/common";
import { AccessTokenAuth } from "./accessTokenAuth.js";
import { KeycloakConfig } from "../config/keycloakConfig.js";
import { ApiKeyAuth } from "./apiKeyAuth.js";
import { KeycloakAuth } from "../constant/keycloak.auth.js";
export class Auth {
static API_KEY = "x-api-key";
static BEARER_TOKEN = "authorization";
request;
constructor(request) {
this.request = request;
}
async validate() {
const keycloakConfig = new KeycloakConfig(process.env.REALM, process.env.AUTH_SERVER_BASE_URL);
const apiKey = this.apiKey();
const accessToken = this.accessToken();
if (accessToken && apiKey) {
throw new ForbiddenException("Bearer token and Api Key cannot be used together");
}
if (accessToken) {
Logger.debug("Authenticate with Access Token...", KeycloakAuth.NAME);
const bearerTokenAuth = new AccessTokenAuth(keycloakConfig);
return bearerTokenAuth.validate(accessToken);
}
if (apiKey) {
Logger.debug("Authenticate with Api Key...", KeycloakAuth.NAME);
const apiKeyAuth = new ApiKeyAuth(keycloakConfig);
return apiKeyAuth.validate(apiKey);
}
throw new ForbiddenException("X-API-KEY or Authorization header missing...");
}
accessToken() {
const authHeader = this.request.headers[Auth.BEARER_TOKEN];
if (!authHeader) {
return undefined;
}
const [type, accessToken] = authHeader.split(" ") ?? [];
return type === "Bearer" ? accessToken : undefined;
}
apiKey() {
return this.request.headers[Auth.API_KEY];
}
}