Skip to content

Commit eec2e5b

Browse files
authored
feat: Add Keycloak auth adapter option audience to validate the access token audience (#10881)
1 parent 84bf633 commit eec2e5b

2 files changed

Lines changed: 159 additions & 3 deletions

File tree

‎spec/AuthenticationAdapters.spec.js‎

Lines changed: 134 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -787,7 +787,7 @@ describe('keycloak auth adapter', () => {
787787
}
788788
});
789789

790-
it('validateAuthData should fail with wrong azp (audience)', async () => {
790+
it('validateAuthData should fail with wrong azp', async () => {
791791
const fakeClaim = {
792792
iss: 'https://auth.example.com/realms/my-realm',
793793
azp: 'other-app',
@@ -1133,6 +1133,139 @@ describe('keycloak auth adapter', () => {
11331133
expect(e.message).toBe('invalid signature');
11341134
}
11351135
});
1136+
1137+
describe('audience', () => {
1138+
const crypto = require('crypto');
1139+
const config = {
1140+
'auth-server-url': 'https://auth.example.com',
1141+
realm: 'my-realm',
1142+
'client-id': 'parse-app',
1143+
};
1144+
let privateKey;
1145+
let publicKey;
1146+
1147+
const signToken = claims =>
1148+
jwt.sign(
1149+
{
1150+
iss: 'https://auth.example.com/realms/my-realm',
1151+
azp: 'parse-app',
1152+
sub: 'user123',
1153+
...claims,
1154+
},
1155+
privateKey,
1156+
{ algorithm: 'RS256', keyid: 'test-key-1', expiresIn: '1h' }
1157+
);
1158+
1159+
const validate = (claims, options) => {
1160+
const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter('keycloak', {
1161+
keycloak: { config, ...options },
1162+
});
1163+
return adapter.validateAuthData(
1164+
{ id: 'user123', access_token: signToken(claims) },
1165+
providerOptions
1166+
);
1167+
};
1168+
1169+
beforeAll(() => {
1170+
({ privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
1171+
modulusLength: 2048,
1172+
publicKeyEncoding: { type: 'spki', format: 'pem' },
1173+
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
1174+
}));
1175+
});
1176+
1177+
beforeEach(() => {
1178+
spyOn(authUtils, 'getSigningKey').and.resolveTo({ kid: 'test-key-1', publicKey });
1179+
});
1180+
1181+
it('validateAuthData should fail with wrong aud when audience is set', async () => {
1182+
await expectAsync(
1183+
validate({ aud: 'other-service' }, { audience: 'parse-server' })
1184+
).toBeRejectedWith(
1185+
jasmine.objectContaining({
1186+
code: Parse.Error.OBJECT_NOT_FOUND,
1187+
message: 'jwt audience invalid. expected: parse-server',
1188+
})
1189+
);
1190+
});
1191+
1192+
it('validateAuthData should fail without aud when audience is set', async () => {
1193+
await expectAsync(validate({}, { audience: 'parse-server' })).toBeRejectedWith(
1194+
jasmine.objectContaining({
1195+
code: Parse.Error.OBJECT_NOT_FOUND,
1196+
message: 'jwt audience invalid. expected: parse-server',
1197+
})
1198+
);
1199+
});
1200+
1201+
it('validateAuthData should accept aud containing the audience', async () => {
1202+
const claims = await validate(
1203+
{ aud: ['account', 'parse-server'] },
1204+
{ audience: 'parse-server' }
1205+
);
1206+
expect(claims.sub).toBe('user123');
1207+
});
1208+
1209+
it('validateAuthData should accept aud matching one of several audiences', async () => {
1210+
const claims = await validate(
1211+
{ aud: 'parse-admin' },
1212+
{ audience: ['parse-server', 'parse-admin'] }
1213+
);
1214+
expect(claims.sub).toBe('user123');
1215+
});
1216+
1217+
it('validateAuthData should not check aud when audience is not set', async () => {
1218+
for (const options of [{}, { audience: undefined }, { audience: null }]) {
1219+
const claims = await validate({ aud: 'other-service' }, options);
1220+
expect(claims.sub).toBe('user123');
1221+
}
1222+
});
1223+
1224+
it('validateAuthData should fail with wrong azp when audience is set', async () => {
1225+
await expectAsync(
1226+
validate({ azp: 'other-app', aud: 'parse-server' }, { audience: 'parse-server' })
1227+
).toBeRejectedWith(
1228+
jasmine.objectContaining({
1229+
code: Parse.Error.OBJECT_NOT_FOUND,
1230+
message:
1231+
'access token is not authorized for this client - expected: parse-app | from: other-app',
1232+
})
1233+
);
1234+
});
1235+
1236+
it('validateAuthData should fail with invalid audience option', async () => {
1237+
for (const audience of ['', [], [''], ['parse-server', 1], 1, {}]) {
1238+
await expectAsync(validate({ aud: 'parse-server' }, { audience })).toBeRejectedWith(
1239+
jasmine.objectContaining({
1240+
code: Parse.Error.OBJECT_NOT_FOUND,
1241+
message: 'Keycloak auth is not configured. Invalid audience.',
1242+
})
1243+
);
1244+
}
1245+
});
1246+
1247+
it('login should fail with wrong aud when audience is set', async () => {
1248+
await reconfigureServer({ auth: { keycloak: { config, audience: 'parse-server' } } });
1249+
await expectAsync(
1250+
Parse.User.logInWith('keycloak', {
1251+
authData: { id: 'user123', access_token: signToken({ aud: 'other-service' }) },
1252+
})
1253+
).toBeRejectedWith(
1254+
jasmine.objectContaining({
1255+
code: Parse.Error.OBJECT_NOT_FOUND,
1256+
message: 'jwt audience invalid. expected: parse-server',
1257+
})
1258+
);
1259+
});
1260+
1261+
it('login should succeed with matching aud when audience is set', async () => {
1262+
await reconfigureServer({ auth: { keycloak: { config, audience: 'parse-server' } } });
1263+
const user = await Parse.User.logInWith('keycloak', {
1264+
authData: { id: 'user123', access_token: signToken({ aud: 'parse-server' }) },
1265+
});
1266+
expect(user.getSessionToken()).toBeDefined();
1267+
});
1268+
});
11361269
});
11371270

11381271
describe('apple signin auth adapter', () => {

‎src/Adapters/Auth/keycloak.js‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
* @param {String} options.config.auth-server-url - The Keycloak authentication server URL.
88
* @param {String} options.config.realm - The Keycloak realm name.
99
* @param {String} options.config.client-id - The Keycloak client ID.
10+
* @param {String|String[]} [options.audience] - The expected access token audience (optional). If set, an access token whose `aud` claim contains none of these values is rejected.
1011
*
1112
* @param {Object} authData - The authentication data provided by the client.
1213
* @param {String} authData.access_token - The Keycloak access token retrieved during client authentication.
@@ -51,8 +52,21 @@
5152
* }
5253
* ```
5354
*
55+
* ## Audience Validation
56+
* Keycloak does not add the client that a token is issued to into the access token audience by default, so Parse Server validates the `aud` claim only if `audience` is set. To use it, add an audience mapper in Keycloak so that the access tokens for Parse Server contain the configured value:
57+
* ```javascript
58+
* {
59+
* "auth": {
60+
* "keycloak": {
61+
* "config": require('./auth/keycloak.json'),
62+
* "audience": "parse-server"
63+
* }
64+
* }
65+
* }
66+
* ```
67+
*
5468
* ## Notes
55-
* - Parse Server validates the provided `authData` by making a `userinfo` call to Keycloak and ensures the attributes match those returned by Keycloak.
69+
* - Parse Server verifies the access token locally with the public keys of the realm. The token must be issued by the realm (`iss`), to the configured `client-id` (`azp`), and for the user `id` (`sub`). The `roles` and `groups` in the auth data must equal the `roles` and `groups` claims of the token.
5670
*
5771
* ## Keycloak Configuration
5872
* To configure Keycloak, copy the JSON configuration file generated from Keycloak's setup guide:
@@ -64,6 +78,7 @@
6478
* For more information on Keycloak authentication, see:
6579
* - [Securing Apps Documentation](https://www.keycloak.org/docs/latest/securing_apps/)
6680
* - [Server Administration Documentation](https://www.keycloak.org/docs/latest/server_admin/)
81+
* - [Audience Support](https://www.keycloak.org/docs/latest/server_admin/#audience-support)
6782
*/
6883

6984
const { Parse } = require('parse/node');
@@ -106,7 +121,7 @@ const getKeycloakKeyByKeyId = async (keyId, jwksUri, cacheMaxEntries, cacheMaxAg
106121

107122
const verifyAccessToken = async (
108123
{ access_token, id, roles, groups } = {},
109-
{ config, cacheMaxEntries, cacheMaxAge } = {}
124+
{ config, cacheMaxEntries, cacheMaxAge, audience } = {}
110125
) => {
111126
if (!(access_token && id)) {
112127
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Missing access token and/or User id');
@@ -120,6 +135,13 @@ const verifyAccessToken = async (
120135
'Keycloak auth is not configured. Missing client-id.'
121136
);
122137
}
138+
const audiences = audience == null ? undefined : [].concat(audience);
139+
if (audiences && !(audiences.length && audiences.every(a => a && typeof a === 'string'))) {
140+
throw new Parse.Error(
141+
Parse.Error.OBJECT_NOT_FOUND,
142+
'Keycloak auth is not configured. Invalid audience.'
143+
);
144+
}
123145

124146
const expectedIssuer = `${config['auth-server-url']}/realms/${config['realm']}`;
125147
const jwksUri = `${config['auth-server-url']}/realms/${config['realm']}/protocol/openid-connect/certs`;
@@ -137,6 +159,7 @@ const verifyAccessToken = async (
137159
try {
138160
jwtClaims = jwt.verify(access_token, signingKey, {
139161
algorithms: ['RS256'],
162+
audience: audiences,
140163
});
141164
} catch (exception) {
142165
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, `${exception.message}`);

0 commit comments

Comments
 (0)