-
Notifications
You must be signed in to change notification settings - Fork 1
/
OidcStrategy.ts
213 lines (173 loc) · 6.59 KB
/
OidcStrategy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import { IncomingMessage } from 'http';
import { AuthenticationResult, JWTStrategy, ConnectionEvent } from '@feathersjs/authentication';
import { NotAuthenticated } from '@feathersjs/errors';
import { Params } from '@feathersjs/feathers';
import Debug from 'debug';
import Verifier, { JWT } from './Verifier';
const debug = Debug('feathers-authentication-oidc/strategy');
export class OidcStrategy extends JWTStrategy {
private verifier!: Verifier;
// Called when strategy is registered
verifyConfiguration(): void {
const allowedKeys = [
'entity', 'entityId', 'service', 'header', 'schemes', 'issuer', 'audience', 'additionalFields', 'parseIssuer',
];
debug(this.configuration);
for (const key of Object.keys(this.configuration)) {
if (!allowedKeys.includes(key)) {
throw new Error(`Invalid OidcStrategy option 'authentication.${this.name}.${key}'. Did you mean to set it in 'authentication'?`);
}
}
this.verifier = new Verifier(this.configuration);
}
// Override to allow different JwtStrategies to use same Header
// @ts-ignore
async parse(req: IncomingMessage): Promise<{
strategy: string;
accessToken: string;
} | null> {
const { parseIssuer } = this.configuration;
const strategy = await super.parse(req);
if (!parseIssuer || strategy === null) return strategy;
// Check if accessToken is issued by this server
const { accessToken = '' } = strategy;
const [, payload = undefined] = accessToken.split('.');
if (!payload) return strategy;
const { iss } = JSON.parse(Buffer.from(payload, 'base64').toString('utf8'));
const { issuer: allowedIssuer } = this.configuration;
const isIssuerValid = (typeof allowedIssuer === 'string' && iss === allowedIssuer) ||
(Array.isArray(allowedIssuer) && allowedIssuer.includes(iss));
if (isIssuerValid) return strategy;
// Ignore access token to fallback to other JwtStrategy
debug('ignoring parsed header value');
return null;
}
async handleConnection(event: ConnectionEvent, connection: any, authResult?: AuthenticationResult): Promise<void> {
const { strategy } = authResult?.authentication || {};
const isValidLogout = event === 'logout' && strategy === this.name;
// Add authentication info only when using current strategy to allow concurrent usage with JwtStrategy.
if (event === 'login' && strategy === this.name) {
debug('Adding authentication information to connection');
connection.authentication = {
strategy: this.name,
accessToken: authResult?.accessToken,
};
} else if (isValidLogout || event === 'disconnect') {
const { entity } = this.configuration;
delete connection[entity];
delete connection.authentication;
}
}
get entityId(): string {
return this.configuration.entityId || this.entityService?.id;
}
/**
* Get query for existing entity using JWT payload
*/
getEntityQuery(decodedJwt: any): any {
return {
[`${this.name}Id`]: decodedJwt.sub || decodedJwt.id
};
}
/**
* Extract data from JWT to for creating or upating of entity.
* @param decodedJwt
* @param _params
*/
getEntityData(decodedJwt: any, _params: Params): any {
debug('getEntityData decodedJwt', decodedJwt);
let entity = {
[`${this.name}Id`]: decodedJwt.sub || decodedJwt.id,
email: decodedJwt.email,
};
const { additionalFields } = this.configuration;
if (additionalFields) {
for (const field of additionalFields) {
entity[field] = decodedJwt[field];
}
}
return entity;
}
async findEntity(decodedJwt: any, params: Params): Promise<any> {
const query = await this.getEntityQuery(decodedJwt);
debug('findEntity with query', query);
if (!this.entityService) {
throw new NotAuthenticated(`Could not find entity service`);
}
const result = await this.entityService.find({
...params,
query
});
const [ entity = null ] = result.data ? result.data : result;
debug('findEntity returning', entity);
return entity;
}
async createEntity(decodedJwt: any, params: Params): Promise<any> {
const data = await this.getEntityData(decodedJwt, params);
debug('createEntity with data', data);
return this.entityService.create(data, params);
}
async updateEntity(entity: any, decodedJwt: any, params: Params): Promise<any> {
const id = entity[this.entityId];
const data = await this.getEntityData(decodedJwt, params);
debug(`updateEntity with id ${id} and data`, data);
return this.entityService.patch(id, data, params);
}
async getEntity(result: any, params: Params): Promise<any> {
const { entityId } = this;
if (!entityId || result[entityId] === undefined) {
throw new NotAuthenticated('Could not get entity for OIDC');
}
if (!params.provider) {
return result;
}
const { entity } = this.configuration;
return this.entityService.get(result[entityId], {
...params,
[entity]: result
});
}
async authenticate(authentication: AuthenticationResult, originalParams: Params): Promise<any> {
const { accessToken, updateEntity = false } = authentication;
const { entity } = this.configuration;
if (!accessToken) {
throw new NotAuthenticated('No access token');
}
const decodedJwt = await this.verifyJwt(accessToken/*, params.jwt*/);
const result: AuthenticationResult = {
// Provide accessToken for Feathers authentication to skip JWT creation in `createAccessToken`
// accessToken also required in auth service create after hook to be added to connection
accessToken,
authentication: {
strategy: this.name || 'oidc',
}
};
if (entity === null) {
return result;
}
// Find entity using internal call by removing provider.
const { provider, ...params } = originalParams;
const existingEntity = await this.findEntity(decodedJwt, params);
debug('authenticate with (existing) entity', existingEntity);
let authEntity: any;
if (!existingEntity) {
authEntity = await this.createEntity(decodedJwt, params)
} else if (updateEntity) {
debug('updating entity', existingEntity);
authEntity = await this.updateEntity(existingEntity, decodedJwt, params);
} else {
authEntity = existingEntity;
}
return {
...result,
[entity]: await this.getEntity(authEntity, originalParams),
};
}
async verifyJwt (token: string): Promise<JWT> {
try {
return this.verifier.verifyJwt(token);
} catch (error) {
throw new NotAuthenticated(error.message, error);
}
}
}