@zigatech/keycloak-auth
Version:
Keycloak authorization library for NestJS. Works out of the box.
75 lines (74 loc) • 3.22 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Auth = void 0;
const common_1 = require("@nestjs/common");
const accessTokenAuth_js_1 = require("./accessTokenAuth.js");
const keycloakConfig_js_1 = require("../config/keycloakConfig.js");
const apiKeyAuth_js_1 = require("./apiKeyAuth.js");
const keycloak_auth_js_1 = require("../constant/keycloak.auth.js");
class Auth {
constructor(request) {
Object.defineProperty(this, "request", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
this.request = request;
}
validate() {
return __awaiter(this, void 0, void 0, function* () {
const keycloakConfig = new keycloakConfig_js_1.KeycloakConfig(process.env.REALM, process.env.AUTH_SERVER_BASE_URL);
const apiKey = this.apiKey();
const accessToken = this.accessToken();
if (accessToken && apiKey) {
throw new common_1.ForbiddenException("Bearer token and Api Key cannot be used together");
}
if (accessToken) {
common_1.Logger.debug("Authenticate with Access Token...", keycloak_auth_js_1.KeycloakAuth.NAME);
const bearerTokenAuth = new accessTokenAuth_js_1.AccessTokenAuth(keycloakConfig);
return bearerTokenAuth.validate(accessToken);
}
if (apiKey) {
common_1.Logger.debug("Authenticate with Api Key...", keycloak_auth_js_1.KeycloakAuth.NAME);
const apiKeyAuth = new apiKeyAuth_js_1.ApiKeyAuth(keycloakConfig);
return apiKeyAuth.validate(apiKey);
}
throw new common_1.ForbiddenException("X-API-KEY or Authorization header missing...");
});
}
accessToken() {
var _a;
const authHeader = this.request.headers[Auth.BEARER_TOKEN];
if (!authHeader) {
return undefined;
}
const [type, accessToken] = (_a = authHeader.split(" ")) !== null && _a !== void 0 ? _a : [];
return type === "Bearer" ? accessToken : undefined;
}
apiKey() {
return this.request.headers[Auth.API_KEY];
}
}
exports.Auth = Auth;
Object.defineProperty(Auth, "API_KEY", {
enumerable: true,
configurable: true,
writable: true,
value: "x-api-key"
});
Object.defineProperty(Auth, "BEARER_TOKEN", {
enumerable: true,
configurable: true,
writable: true,
value: "authorization"
});