I have cloned from git the Auth0 code-example for basic-role-based-access-control
(using react, nodejs, and javascript).
I am happy how it runs, now trying to get some learnings from the example by inspecting the code. Then I stumbled over the following fragment of code, which is pretty essential for the rbac:
const checkRequiredPermissions = (requiredPermissions) => {
return (req, res, next) => {
const permissionCheck = claimCheck((payload) => {
const permissions = payload.permissions || [ ];
const hasPermissions = requiredPermissions.every((requiredPermission) =>
permissions.includes(requiredPermission)
);
if (!hasPermissions) {
throw new InsufficientScopeError();
}
return hasPermissions;
});
permissionCheck(req, res, next);
};
};
My question is: where does the function argument payload
get its value assigned, and why isn’t used req.auth.payload
?
tyf
June 17, 2024, 9:52pm
3
Hello @martin617 !
Great Question - The payload
(JWTPayload
) is provided implicitly by the claimCheck
function :
}
return payload[claim] === expected;
}, `Unexpected '${claim}' value`);
};
export type ClaimCheck<R = ClaimChecker> = (
fn: (payload: JWTPayload) => boolean,
errMsg?: string
) => R;
export const claimCheck: ClaimCheck = (fn, errMsg) => {
if (typeof fn !== 'function') {
throw new TypeError("'claimCheck' expects a function");
}
return (payload?: JWTPayload) => {
if (!payload) {
throw new UnauthorizedError();
}
if (!fn(payload)) {
throw new InvalidTokenError(errMsg);
Hope this helps to clarify!
Thank you, tyf!
In the node/express version of code which I am using, I guess it is happening here.
Thanks for helping me on the discovery path.
const toHandler = (fn) => (req, res, next) => {
var _a;
try {
fn((_a = req.auth) === null || _a === void 0 ? void 0 : _a.payload);
next();
}
catch (e) {
next(e);
}
};
const claimCheck = (...args) => toHandler(claimCheck$1(...args));
1 Like
tyf
June 18, 2024, 2:41pm
5
No problem, happy to help and thanks for sharing!
system
Closed
July 2, 2024, 2:41pm
6
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.