Skip to content

Commit 6e36203

Browse files
authored
fix profile object of keycloak to ensure all data is transferred back to consumer (#43)
Fixes #42
1 parent 7d7e8f2 commit 6e36203

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed

src/strategies/passport/passport-keycloak/keycloak-strategy-factory-provider.ts

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,59 @@ export class KeycloakStrategyFactoryProvider
5555
},
5656
);
5757

58+
// Override user profile fn of underlying library
59+
strategy.userProfile = (
60+
accessToken: string,
61+
done: (err: unknown, userInfo?: unknown) => void,
62+
) => {
63+
this._userProfileFn(strategy, accessToken, done);
64+
};
65+
5866
this._setupProxy(strategy);
5967
return strategy;
6068
}
6169

62-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
63-
private _setupProxy(strategy: any) {
70+
private _userProfileFn(
71+
strategy: typeof KeycloakStrategy,
72+
accessToken: string,
73+
done: (err: unknown, userInfo?: KeycloakProfile) => void,
74+
) {
75+
// Credits - https://github.com/exlinc/keycloak-passport/blob/eaa3859f83619d8e349e87193fdf8acc3a3d0ba9/index.js#L28
76+
strategy._oauth2._useAuthorizationHeaderForGET = true;
77+
strategy._oauth2.get(
78+
strategy.options.userInfoURL,
79+
accessToken,
80+
(err: unknown, body: string) => {
81+
if (err) {
82+
return done(err);
83+
}
84+
85+
try {
86+
const json = JSON.parse(body);
87+
const email = json.email;
88+
const userInfo: KeycloakProfile = {
89+
keycloakId: json.sub,
90+
fullName: json.name,
91+
firstName: json.given_name,
92+
lastName: json.family_name,
93+
username: json.preferred_username,
94+
email,
95+
avatar: json.avatar,
96+
realm: strategy.options.realm,
97+
// add all attributes to userInfo
98+
// overridden stuff
99+
...json,
100+
};
101+
102+
done(null, userInfo);
103+
} catch (e) {
104+
done(e);
105+
}
106+
},
107+
);
108+
}
109+
110+
private _setupProxy(strategy: typeof KeycloakStrategy) {
64111
// Setup proxy if any
65112
let httpsProxyAgent;
66113
if (process.env['https_proxy']) {

src/strategies/types.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,4 +89,6 @@ export interface KeycloakProfile {
8989
email: string;
9090
avatar: string;
9191
realm: string;
92+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
93+
[key: string]: any;
9294
}

0 commit comments

Comments
 (0)