Created
March 21, 2019 16:03
-
-
Save danew/7919cfaa3cbf640009e371db62e5488d to your computer and use it in GitHub Desktop.
PKCE in the browser
This file contains hidden or 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
// https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_3_%E2%80%93_rewrite_the_DOMs_atob()_and_btoa()_using_JavaScript's_TypedArrays_and_UTF-8 | |
const base64 = require('base64-js'); | |
const urlSafe = (buffer) => { | |
const bytes = new Uint8Array(buffer); | |
return base64.fromByteArray(bytes) | |
.replace(/\+/g, '-') | |
.replace(/\//g, '_') | |
.replace(/=/g, ''); | |
}; | |
const generateCodeVerifier = () => { | |
const bytes = crypto.getRandomValues(new Uint8Array(32)); | |
return urlSafe(bytes); | |
}; | |
const createCodeChallenge = async (verifier) => { | |
const bytes = new TextEncoder().encode(verifier); | |
const buffer = await crypto.subtle.digest('SHA-256', bytes); | |
return urlSafe(new Uint8Array(buffer)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment