@zigatech/keycloak-auth
Version:
Keycloak authorization library for NestJS. Works out of the box.
38 lines (37 loc) • 1.59 kB
JavaScript
import * as jwt from "jsonwebtoken";
import { Logger } from "@nestjs/common";
import { Principal } from "./principal.js";
import { KeycloakAuth } from "../constant/keycloak.auth.js";
export class AccessTokenAuth {
keycloakConfig;
constructor(keycloakConfig) {
this.keycloakConfig = keycloakConfig;
}
async validate(accessToken) {
const pubKey = await this.keycloakConfig.publicKey();
const authTokenPayload = this.verifyToken(accessToken, pubKey);
Logger.log("Access token verified!", KeycloakAuth.NAME);
return new Principal(this.userId(authTokenPayload), authTokenPayload.email, authTokenPayload.email_verified, authTokenPayload.family_name, authTokenPayload.given_name, authTokenPayload.phone_number, authTokenPayload.realm_access.roles);
}
userId(tokenPayload) {
return tokenPayload.zigaUserId ?? tokenPayload.sub;
}
verifyToken(userToken, pubKey) {
let decodedToken;
try {
decodedToken = jwt.verify(userToken, pubKey, {
algorithms: ["RS256"],
complete: false,
});
}
catch (err) {
Logger.error(`Failed to verify access token: ${err.message}`, KeycloakAuth.NAME);
throw new jwt.JsonWebTokenError(err.message, err);
}
if (typeof decodedToken === "string") {
Logger.error(`Invalid token Payload: ${decodedToken}`, KeycloakAuth.NAME);
throw new jwt.JsonWebTokenError(`Invalid token payload: ${decodedToken}`);
}
return decodedToken;
}
}