-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathstate-pkce.ts
More file actions
66 lines (58 loc) · 2.01 KB
/
state-pkce.ts
File metadata and controls
66 lines (58 loc) · 2.01 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
/*
* @forgerock/javascript-sdk
*
* state-pkce.ts
*
* Copyright (c) 2020 - 2025 Ping Identity Corporation. All rights reserved.
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
import PKCE from '../util/pkce';
import { GetAuthorizationUrlOptions } from './interfaces';
function getStorageKey(clientId: string, prefix?: string) {
return `${prefix || 'FR-SDK'}-authflow-${clientId}`;
}
/**
* Generate and store PKCE values for later use
* @param { string } storageKey - Key to store authorization options in sessionStorage
* @param {GenerateAndStoreAuthUrlValues} options - Options for generating PKCE values
* @returns { state: string, verifier: string, GetAuthorizationUrlOptions }
*/
interface GenerateAndStoreAuthUrlValues extends GetAuthorizationUrlOptions {
clientId: string;
login?: 'redirect' | 'embedded';
prefix?: string;
}
export function generateAndStoreAuthUrlValues(options: GenerateAndStoreAuthUrlValues) {
const verifier = PKCE.createVerifier();
const state = PKCE.createState();
const storageKey = getStorageKey(options.clientId, options.prefix);
const authorizeUrlOptions = {
...options,
state,
verifier,
};
return [
authorizeUrlOptions,
() => sessionStorage.setItem(storageKey, JSON.stringify(authorizeUrlOptions)),
] as const;
}
/**
* @function getStoredAuthUrlValues - Retrieve stored authorization options from sessionStorage
* @param { string } clientId - Client ID
* @param { string } [prefix] - Prefix for storage key
* @returns { GetAuthorizationUrlOptions | null }
*/
export function getStoredAuthUrlValues(
clientId: string,
prefix?: string,
): GetAuthorizationUrlOptions | null {
const storageKey = getStorageKey(clientId, prefix);
const storedString = sessionStorage.getItem(storageKey);
sessionStorage.removeItem(storageKey);
try {
return JSON.parse(storedString as string);
} catch (error) {
throw new Error('Stored values for Auth URL could not be parsed');
}
}