UNPKG

@zigatech/keycloak-auth

Version:

Keycloak authorization library for NestJS. Works out of the box.

36 lines (35 loc) 1.23 kB
import { Logger } from "@nestjs/common"; import { KeycloakAuth } from "../constant/keycloak.auth.js"; export class KeycloakConfig { realm; authServerUrl; pubKey; constructor(realm, authServerUrl) { this.realm = realm; this.authServerUrl = authServerUrl; } getRealm() { return this.realm; } getAuthServerUrl() { return this.authServerUrl; } async publicKey() { if (this.pubKey) { return this.pubKey; } const CERT_HEADER = "-----BEGIN PUBLIC KEY-----\n"; const CERT_FOOTER = "\n-----END PUBLIC KEY-----"; try { const response = await fetch(`${this.authServerUrl}/realms/${this.realm}`); const data = await response.json(); Logger.debug("Obtained public key for jwt token verification.", KeycloakAuth.NAME); this.pubKey = `${CERT_HEADER}${data["public_key"]}${CERT_FOOTER}`; return this.pubKey; } catch (err) { Logger.error(`Could not obtain public key for jwt token verification: ${err.message}`, KeycloakAuth.NAME); throw new Error("Could not obtain public key for jwt token verification!"); } } }