SSO Authentication with React Native

August 17, 2022

SSO Authentication with React Native

SSO Authentication with React Native

Navigator.js

Note : Follow the react navigation deep linking for url-scheme for android or iOS

E.g npx uri-scheme add appauth —ios

import React from 'react'
import Home from './Home';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
const RootStack = createNativeStackNavigator();

  const linking = {
    prefixes: ['appauth://'],
    config: {
      initialRouteName: 'Home',
      screens: {
        Home: {
          path: 'home'
        }
      }
    } 
  };
  
  const RootNavigator = () => { 
    return (
      <NavigationContainer
        linking={linking}
        > 
        <RootStack.Navigator>
          <RootStack.Screen name="Home" component={Home} />
        </RootStack.Navigator> 
      </NavigationContainer>
    );
  };

export default RootNavigator

Home.js

import { View, Alert, Button, Text, ScrollView } from 'react-native'
import React, { useCallback, useState } from 'react'
import { authorize } from 'react-native-app-auth';



const config = {
  issuer: 'https://dev-eqxk........auth0.com',
  clientId: 'yTCYU......yUCb.......LFKCx',
  redirectUrl: 'appauth://home',
  scopes: ['openid','profile','email'],
};   

    
const Home = () => {
const [Token, SetToken]:any = useState(null)
const CallLogin=useCallback(async()=>{
  try {
    const result = await authorize(config);
    SetToken(result)
  } catch (error:any) {
    Alert.alert(error.message);
  }
},[])

  return (
    <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
      <Button onPress={() => CallLogin()}
              title="Authorize IdentityServer"
              color="#DA2536"
            />

            {Token&&
              <ScrollView style={{margin:10}}>
                 <Text>Access Token: {JSON.stringify(Token)}</Text> 
              </ScrollView> 
            }
    </View>
  )
}

export default Home

Written by Manoj Bhardwaj who lives and works in Dharamshala Himachal Pradesh (India). My stackoverflow