-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathexhange_token.ts
More file actions
74 lines (71 loc) · 2.57 KB
/
exhange_token.ts
File metadata and controls
74 lines (71 loc) · 2.57 KB
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
/**
* @license
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Auth } from '../../model/public_types';
import { _isFirebaseServerApp } from '@firebase/app';
import { exchangeToken as getToken } from '../../api/authentication/exchange_token';
import { _serverAppCurrentUserOperationNotSupportedError } from '../../core/util/assert';
import { EXCHANGE_TOKEN_PARENT } from '../../api';
import { _castAuth } from '../auth/auth_impl';
/**
* Asynchronously exchanges an OIDC provider's Authorization code or Id Token
* for a Firebase Token.
*
* @remarks
* This method is implemented only for `DefaultConfig.REGIONAL_API_HOST` and
* requires {@link TenantConfig} to be configured in the {@link Auth} instance used.
*
* Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.
*
* @param auth - The {@link Auth} instance.
* @param idpConfigId - The ExternalUserDirectoryId corresponding to the OIDC custom Token.
* @param customToken - The OIDC provider's Authorization code or Id Token to exchange.
* @returns The firebase access token (JWT signed by Firebase Auth).
*
* @public
*/
export async function exchangeToken(
auth: Auth,
idpConfigId: string,
customToken: string
): Promise<string> {
if (_isFirebaseServerApp(auth.app)) {
return Promise.reject(
_serverAppCurrentUserOperationNotSupportedError(auth)
);
}
const authInternal = _castAuth(auth);
const token = await getToken(authInternal, {
parent: buildParent(auth, idpConfigId),
token: customToken
});
if (token) {
await authInternal._updateFirebaseToken({
token: token.accessToken,
expirationTime: Date.now() + token.expiresIn * 1000
});
}
return token.accessToken;
}
function buildParent(auth: Auth, idpConfigId: string): string {
return EXCHANGE_TOKEN_PARENT.replace(
'${projectId}',
auth.app.options.projectId ?? ''
)
.replace('${location}', auth.tenantConfig?.location ?? '')
.replace('${tenantId}', auth.tenantConfig?.tenantId ?? '')
.replace('${idpConfigId}', idpConfigId);
}