OKTA React Native Authentication

Williams Sissoko
5 min readAug 11, 2018

Welcome! This is a basic introduction on how to implement authentication with okta using react-native.

My name is Williams Sissoko, I’m currently a student studying abroad in Thailand, also a big fan of React Native.

Earlier this month after working on a 3 month long project I stumbled upon a serviced called OKTA. At first, I was a bit skeptical using a third party user authentication service but it saved a ton of time building my project.

Check out the final project here:

https://github.com/wcisco17/OKTA-Expo-Auth

So after experimenting with the service and being 3 months in learning React I decided to build a pretty simple app that showcase OKTA with React Native.

Awesome now let’s dive right in! (Also this blog assumes you’re somewhat familiar with react and react-native, and the command line)

For this project I used the create-react-native-app boilerplate to get myself up to speed and you can install it by doing so,

npm install create-react-native-app — save

After that’s all done go ahead and run this command in your terminal

create-react-native-app {yourAppName}

Now if that doesn’t work try

npx create-react-native-app {yourAppName}

All set it up? Now move into your folder directory and delete everything in your return statement including your Stylesheet you won’t be needing those.

import Index from ‘./client/index’

It should look like this so far

import React from 'react';import {Text, View } from 'react-native';import Index from './client/Index'export default class App extends React.Component {    render() {        return (            <Index />        );     }  }

Inside the index file should look like this,

import React, { Component } from 'react'import { Text, View } from 'react-native'export default class Index extends Component {    render() {      return (          <View>            <Text>Index</Text>          </View>       )    }}

Now we need a couple dependencies before starting, in your terminal go ahead and run

yarn add @okta/okta-react-native react-native-elements

Before you can use Okta you need to create an account at https://developer.okta.com/signup/. Go ahead and enter any company name you would like. Once you confirmed your email and signed up

Follow the steps to Set Up your Application,

  • From the Applications page, choose Add Application.
  • On the Create New Application page, select NATIVE APP (IOS & ANDROID).
  • Fill-in the Application Settings, then click Done.

Now before you go anywhere make sure your page looks exactly like this and in the login settings make sure you add this to the login redirect uri:

exp://localhost:19000/+expo-auth-session

MAKE SURE your application page looks like this everything you need will be on this page so double check!! Also this is for developers using expo.

Your page should look exactly like this

Let’s return to the app before we grab anything, in your client directory go ahead and create a

Folder: name it api. Go inside this folder and create a file call it TokenClient.js.

Inside your TokenClient page we need to import token client from @okta/okta-react-native, this will return an object that takes in an issuer, client_id, scope, and redirect_uri.

// TokenClient.jsimport TokenClient from '@okta/okta-react-native'export default tokenClient = new TokenClient({
issuer: '
https://{yourOktaDomain}.com/oauth2/default',
client_id: '{clientId}',
scope: 'openid profile',
redirect_uri: __DEV__ ?
'exp://localhost:19000/+expo-auth-session' :
'com.{yourReversedOktaDomain}:/callback',
});

The issuer should be in the API first section called Authorization servers:

Your client id and redirect uri should be in the very first picture!

Alright you should be all set! Now let’s finally write some code, in your client directory create a new file called index.js. In here we are going to import a few things..

import React, { Component } from 'react'import { View } from 'react-native'import tokenClient from './api/TokenClient'import { Button, Text } from 'react-native-elements';// Then let’s create our class called index and add some state to it, our first function will be using async + await to check if the token client is authenticated or not.export default class Index extends Component {   state = {        authentication: false, // Setting the original state to be false value.     }checkAuthentication = async () =>  {const { authentication } = this.state;const authenticated = await tokenClient.isAuthenticated()// We are storing this promise into authenticated then it will return a boolean based on if the user is a token client or not. The current “const authenticated” will always be false unless the user is true.if (authenticated !== authentication)   {   this.setState({ authentication: authenticated })// Now we are storing the old state of authentication into our new authenticated variable based on if the user is token client or not.      } }// Right after this we call componentDidMount to await until the authentication is true and a login function that returns a promise of the clients “access_token” and “id_token”.    async componentDidMount() {      await this.checkAuthentication()    }logIn = async() => {     await tokenClient.signInWithRedirect()    .then((res) => {     console.log("Success", res)   })   .catch((err) => {   console.log("Error", err) })   this.checkAuthentication()}// We can’t forget to log out!logOut = async() => {    await tokenClient.signOut()    this.checkAuthentication()}// Last but not least, we are grabbing back our original state from before and creating an if or else statement with a (ternary) operator.  render() {    const { authentication } = this.state; 
// Deconstructing using brackets allows us to write “authentication” instead of “this.state.authentication”
return ( <View>{/* This essentially reads like this: if the authentication statement is true, then take me to the welcome page or else. If it’s false, take me to the sign in page. /*} {authentication ? <View> <Text>Welcome!</Text> <Button title="Sign Out" onPress={async() => {this.logOut()}} /> </View> : // Or else <View style={{ padding: 100 }} > <Button title="Sign In" onPress={async() => {this.logIn()}} /> </View> } </View> ) }}

Alright we should be good to go you can edit this however you like I wanted to make it as simple as possible for you to get it up and running and save time authenticating users. Now if you would like to modify it, fork or download the finish version on git-hub!

This is also my first blog post on medium so feel free to free to leave some feedback, I just started my coding journey in January fell in love with it ever since. I have a ton of free time so expect more content to come out soon!

https://github.com/wcisco17/OKTA-Expo-Auth

Next time I will implement the same application but with Redux!

--

--