Home Generate PKCE challenge in React Native
Post
Cancel

Generate PKCE challenge in React Native

auth0’s post titled “Which OAuth 2.0 Flow Should I Use?” recommends that you use Authorization Code Flow with Proof Key for Code Exchange (PKCE) flow for you mobile apps.

What is PKCE?

PKCE (pronounced ‘pixy’) offers more secure Authorization Code flow that is originally designed to protect mobile apps, but is now important for all OAuth clients.

From the official OAuth 2.0 spec for PKCE:

PKCE (RFC 7636) is an extension to the Authorization Code flow to prevent CSRF and authorization code injection attacks.


On web apps, generating PKCE challenge is straightforward with Web Crypto API, but in React Native this isn’t available.

Lucky for us, there is already a module that handles this.

Step 1: Create a blank React Native project.

1
2
$ npx react-native init sample
$ cd sample

Skip this step when you already have a functioning app.

Step 2: Install the react-native-pkce-challenge module.

1
$ yarn add react-native-pkce-challenge

Run the next command if you’re also supporting iOS.

1
$ npx pod-install ios

Since this module contains native code, you need to rebuild your project.

Step 3: Using the react-native-pkce-challenge module.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import React from 'react';
import { SafeAreaView, Text } from 'react-native';
import pkceChallenge from 'react-native-pkce-challenge';

const challenge = pkceChallenge();

export default function App() {
  return (
    <SafeAreaView>
      <Text>Challenge: {challenge.codeChallenge}</Text>
      <Text>Verifier: {challenge.codeVerifier}</Text>
    </SafeAreaView>
  );
}

The constant challenge holds an object like the following:

1
2
3
4
{
  codeChallenge: 'XsRstqNrXT76Iop3uMoyyCQmaGthJbKKJwXBSoQXaRk',
  codeVerifier: 'OZOHUwLddiPyTFJulnUYnU9jsf7oyULflbFpwj40bE9S77iaeisGvzvaVvvPE7oO-xaV4skxwKDFBBV7JofVNxCgUSauqUDVcVjggE4-M6zthVUmeUrSAHatmIBm_P0_'
}

You can now use this pair when requesting to your OAuth provider.

This post is licensed under CC BY 4.0 by the author.

Change Android navigation bar color in React Native

Detect outside press in React Native