Created
August 6, 2019 23:00
-
-
Save fabe/c1017f46dbcf8e016fedbc19e8a19268 to your computer and use it in GitHub Desktop.
Create a `verifier` and `challenge` in Expo (React Native) for the Authorization Code Grant Flow with PKCE (Auth0)
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
// Usage: | |
// const [verifier, challenge] = await createVerifierChallenge(); | |
import * as Random from 'expo-random'; | |
import * as Crypto from 'expo-crypto'; | |
if (typeof Buffer === 'undefined') { | |
global.Buffer = require('buffer').Buffer; | |
} | |
function base64URLEncode(str) { | |
return str | |
.toString('base64') | |
.replace(/\+/g, '-') | |
.replace(/\//g, '_') | |
.replace(/=/g, ''); | |
} | |
export const createVerifierChallenge = () => { | |
return new Promise(async (resolve, reject) => { | |
const randomBytes = await Random.getRandomBytesAsync(32); | |
const verifier = base64URLEncode(Buffer.from(randomBytes)); | |
const challengeBase64 = await Crypto.digestStringAsync( | |
Crypto.CryptoDigestAlgorithm.SHA256, | |
verifier, | |
{ encoding: Crypto.CryptoEncoding.BASE64 } | |
); | |
const challenge = challengeBase64 | |
.replace(/\+/g, '-') | |
.replace(/\//g, '_') | |
.replace(/=/g, ''); | |
resolve([verifier, challenge]); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, thanks