Enforcing routes based on URL parameter

Hi,

How can I use keycloak.enforce() based on an parameter provided in the URL?

The Keycloak server is set up so that if I send a hardcoded resource ID to keycloak.enforcer(), it enforces correctly. How can I get it to enforce on a dynamic ID?

With Typescript / Express routing and the keycloak-connect module:

{
 path: "/companies/:orgid",
 method: "get",
 handler: [
 keycloak.enforcer(req.params.orgid),  // <-- How to get hold of the req object so we can send it to keycloak?
async ( req: Request,res: Response): Promise<void> => {
 // enforcer approved the token, handle logic here
}

The other option I’m exploring is to try to protect the route by using keycloak.protect() and evaluating the response from the enforcer, but how can I do that?

Protect route by:
keycloak.protect(protectByOrgID),

protectByOrgID:
export const protectByOrgID = (token: Token, req: Request): boolean => {
const rh: RequestHandler = keycloak.enforcer(req.params.orgid);
console.log(rh.toString()); // returns the function from enforcement function
// How to evaluate the RequestHandler returned from keycloak.enforcer() and return true or false?
};

1 Like

@ robertwinter Did you ever sort this out? I thought I had a working solution, but even if protectByOrganization returns false, it doesn’t automatically send a 403 “Access Denied” response, unfortunately. I have a feeling it makes sense to just do this without Keycloak.

function protectByOrganization(token, req) {
    console.log('*** protectByOrganization: req.params -->', req.params)
    // Do your checks in here.
}

router.param('organizationId', function (req, res, next, value, param { 
    keycloak.protect(protectByOrganization(req.kauth.grant.access_token, req)
   ...
}