Skip to content

Commit fdaeb6b

Browse files
committed
feat(auth): add role mapping and assignment on jwt claims
1 parent cb3d110 commit fdaeb6b

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/service/passport/jwtAuthHandler.js

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,28 @@ async function validateJwt(token, authorityUrl, clientID, expectedAudience) {
6363
}
6464
}
6565

66+
/**
67+
* Assign roles to the user based on the role mappings provided in the jwtConfig.
68+
*
69+
* If no role mapping is provided, the user will not have any roles assigned (i.e. user.admin = false).
70+
* @param {*} roleMapping the role mapping configuration
71+
* @param {*} payload the JWT payload
72+
* @param {*} user the req.user object to assign roles to
73+
*/
74+
function assignRoles(roleMapping, payload, user) {
75+
if (roleMapping) {
76+
for (const role of Object.keys(roleMapping)) {
77+
const claimValuePair = roleMapping[role];
78+
const claim = Object.keys(claimValuePair)[0];
79+
const value = claimValuePair[claim];
80+
81+
if (payload[claim] && payload[claim] === value) {
82+
user[role] = true;
83+
}
84+
}
85+
}
86+
}
87+
6688
const jwtAuthHandler = () => {
6789
return async (req, res, next) => {
6890
const apiAuthMethods = require('../../config').getAPIAuthMethods();
@@ -80,7 +102,7 @@ const jwtAuthHandler = () => {
80102
return res.status(401).send("No token provided\n");
81103
}
82104

83-
const { clientID, authorityURL, expectedAudience } = jwtAuthMethod.jwtConfig;
105+
const { clientID, authorityURL, expectedAudience, roleMapping } = jwtAuthMethod.jwtConfig;
84106
const audience = expectedAudience || clientID;
85107

86108
if (!authorityURL) {
@@ -98,6 +120,8 @@ const jwtAuthHandler = () => {
98120
}
99121

100122
req.user = verifiedPayload;
123+
assignRoles(roleMapping, verifiedPayload, req.user);
124+
101125
return next();
102126
}
103127
}

0 commit comments

Comments
 (0)