getAccessToken(request) { let tokens = this.keyCloak.stores[1].get(request); let result = tokens && tokens.access_token; return result ? Promise.resolve(result) : Promise.reject('There is not token.'); }
/** * Protect with checking authentication only. * * @returns protect middleware */ justProtect() { return this.keyCloak.protect(); }
loginUser(login, password, request, response) { return this.keyCloak.grantManager.obtainDirectly(login, password).then(grant => { this.keyCloak.storeGrant(grant, request, response); return grant; }); }
protectAndCheckPermission(request, response, next, resource, scope) { this.keyCloakProtect(request, response, () => this.checkPermission(request, resource, scope) .then(() => next()).catch(error => { console.error('access denied: ' + error.message); this.keyCloak.accessDenied(request, response); })); }
createSecurityMiddleware() { return (req, res, next) => { if (this.permissions.isNotProtectedUrl(req)) { return next(); } const permission = this.permissions.findPermission(req); if (!permission) { console.log('Can not find a permission for: %s %s', req.method, req.originalUrl); return this.keyCloak.accessDenied(req, res); } this.protectAndCheckPermission(req, res, next, permission.resource, permission.scope); }; }
static initKeyCloak(config) { let result = new Keycloak( { cookies: true }, KeyCloakService.createKeyCloakConfig(config) ); // replace CookieStore from keycloak-connect result.stores[1] = KeyCloakCookieStore; // disable redirection to Keycloak login page result.redirectToLogin = () => false; // TODO It is not necessary, this function returns 403 by default. Just to having redirect to a page. // This function is used in other KeyCloakService methods result.accessDenied = (request, response) => response.redirect('/accessDenied.html'); return result; }
/** * * @param permissions * @param config can be: * undefined (not specified) - the configuration will be loaded from 'keycloak.json' * string - config will be loaded from a file * object - parameters from this object */ constructor(permissions, config) { this.permissions = permissions; this.keyCloak = KeyCloakService.initKeyCloak(config); this.keyCloakProtect = this.keyCloak.protect(); this.entitlementUrl = KeyCloakService.createEntitlementUrl(this.keyCloak); }
middleware(logoutUrl) { // Return the Keycloak middleware. // // Specifies that the user-accessible application URL to // logout should be mounted at /logout // // Specifies that Keycloak console callbacks should target the // root URL. Various permutations, such as /k_logout will ultimately // be appended to the admin URL. let result = this.keyCloak.middleware({ logout: logoutUrl, admin: '/' }); result.push(this.createSecurityMiddleware()); return result; }
accessDenied(request, response) { this.keyCloak.accessDenied(request, response); }