Skip to content

Instantly share code, notes, and snippets.

@fabe
Created August 6, 2019 23:00
Show Gist options
  • Save fabe/c1017f46dbcf8e016fedbc19e8a19268 to your computer and use it in GitHub Desktop.
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)
// 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]);
});
};
@KaizenTamashi
Copy link

Hi, does this work with react-native init projects?

@fabe
Copy link
Author

fabe commented May 7, 2020

Hi, does this work with react-native init projects?

@1kvnlee It should also work for regular RN projects, but you would need to change the Random and Crypto dependencies from Expo to e.g. https://github.com/tradle/react-native-crypto

@KaizenTamashi
Copy link

@fabe Thank you

@ogtfaber
Copy link

Nice, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment