@@ -63,6 +63,28 @@ async function validateJwt(token, authorityUrl, clientID, expectedAudience) {
63
63
}
64
64
}
65
65
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
+
66
88
const jwtAuthHandler = ( ) => {
67
89
return async ( req , res , next ) => {
68
90
const apiAuthMethods = require ( '../../config' ) . getAPIAuthMethods ( ) ;
@@ -80,7 +102,7 @@ const jwtAuthHandler = () => {
80
102
return res . status ( 401 ) . send ( "No token provided\n" ) ;
81
103
}
82
104
83
- const { clientID, authorityURL, expectedAudience } = jwtAuthMethod . jwtConfig ;
105
+ const { clientID, authorityURL, expectedAudience, roleMapping } = jwtAuthMethod . jwtConfig ;
84
106
const audience = expectedAudience || clientID ;
85
107
86
108
if ( ! authorityURL ) {
@@ -98,6 +120,8 @@ const jwtAuthHandler = () => {
98
120
}
99
121
100
122
req . user = verifiedPayload ;
123
+ assignRoles ( roleMapping , verifiedPayload , req . user ) ;
124
+
101
125
return next ( ) ;
102
126
}
103
127
}
0 commit comments