Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
// https://www.oauth.com/playground/authorization-code-with-pkce.html | ||
|
||
/** | ||
* Step 1 - 1 | ||
* | ||
* Generate code verifier | ||
*/ | ||
const generateCodeVerifier = (length: number = 43): string => { | ||
let len: number = length | ||
if (len < 43) len = 43 | ||
if (len > 128) len = 128 | ||
|
||
const randomArr = window.crypto.getRandomValues(new Uint8Array(len)) | ||
const validChars = | ||
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~' | ||
|
||
let codeVerifier = '' | ||
|
||
for (const i of randomArr) { | ||
codeVerifier += validChars[i % len] | ||
} | ||
|
||
return codeVerifier | ||
} | ||
|
||
/** | ||
* Step 1 -2 | ||
* | ||
* Generate code challenge | ||
*/ | ||
const generateCodeChallenge = async (codeVerifier: string): Promise<string> => { | ||
const data = new TextEncoder().encode(codeVerifier) | ||
const hash = await crypto.subtle.digest('SHA-256', data) | ||
return btoa(String.fromCharCode(...new Uint8Array(hash))) | ||
.replace(/\+/g, '-') | ||
.replace(/\//g, '_') | ||
.replace(/=+$/, '') | ||
} |