@react-keycloak/keycloak-ts
Version:
Keycloak typescript adapter
40 lines (35 loc) • 1.5 kB
JavaScript
/* eslint-disable no-useless-escape */
import { fromByteArray } from 'base64-js';
import { sha256 } from 'js-sha256';
function generateRandomString(len, alphabet) {
const randomData = generateRandomData(len);
const chars = [...Array(len)].map((_, idx) => alphabet.charCodeAt(randomData[idx] % alphabet.length));
return String.fromCharCode.apply(null, chars);
}
function generateRandomData(len) {
return [...Array(len)].map(() => Math.floor(256 * Math.random()));
}
export function generateCodeVerifier(len) {
return generateRandomString(len, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
}
const hexDigits = '0123456789abcdef';
export function createUUID() {
const s = generateRandomString(36, hexDigits).split('');
s[14] = '4'; // eslint-disable-next-line no-bitwise
s[19] = hexDigits.substr(s[19] & 0x3 | 0x8, 1);
s[8] = s[13] = s[18] = s[23] = '-';
return s.join('');
}
export function generatePkceChallenge(pkceMethod, codeVerifier) {
switch (pkceMethod) {
// The use of the "plain" method is considered insecure and therefore not supported.
case 'S256':
// hash codeVerifier, then encode as url-safe base64 without padding
const hashBytes = new Uint8Array(sha256.arrayBuffer(codeVerifier));
const encodedHash = fromByteArray(hashBytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
return encodedHash;
default:
throw 'Invalid value for pkceMethod';
}
}
//# sourceMappingURL=uuid.js.map