I am trying to implement OAuth 2 with the expo-auth-session
module.
My user is able to authenticate and is redirected to my backend web server, which is able to recieve the authentication code from the API provider. I was able to do so without using expo-auth-session
package.
What I want now is to fire a callback function that prints the provider’s response (the one that is sent to my redirect uri) or at least the complete url (with get parameters) the response is sent to. From what I understand, expo-auth-session
should allow me to do so.
Note : I cannot provide a custom scheme
because the provider only allows http
and https
schemes. Regardless, when the user is redirected, the application should be able to parse the query parameters and to trigger a callback.
Here is my code :
import React, { useState } from 'react';
import * as WebBrowser from 'expo-web-browser';
import { makeRedirectUri, useAuthRequest } from 'expo-auth-session';
import { Button, Platform } from 'react-native';
WebBrowser.maybeCompleteAuthSession(); // useless on native
// Endpoint
const discovery = {
authorizationEndpoint: 'https://provider.com/oauth/authorize',
tokenEndpoint: 'http://192.168.1.8:8080/token', // <-- I'm not really sure exactly what this should be? My guess is my own backend should return a token to identify my users who authenticated with the API. At least that's what I would like to do.
};
const useProxy = Platform.select({ web: false, default: true }); // not using this right now
export default function App() {
const [step, setStep] = useState('start'); //
const [request, response, promptAsync] = useAuthRequest(
{
':region': 'eu',
clientId: 'myClientId',
scopes: ['wow.profile'],
responseType: 'code',
redirectUri: 'http://192.168.1.8:8080/login', // this is my backend's route where I retrieve the user's authentication code,
// prompt: Prompt.None,
state: 'someteststate', // yes I know this isn't good practice but this is just for testing.
extraParams: { 'customProviderKey': 'value' }
},
discovery
);
React.useEffect(() => {
if (response?.type === 'success') {
const { code } = response.params;
console.log(code);
} else if (response) {
console.log(response);
} else {
console.log("No response..."); // this fires when the component is loaded, before the user authenticates.
}
}, [response]);
return (
<Button
disabled={!request}
title="Login"
onPress={() => {
promptAsync({ useProxy });
}}
/>
);
}
I should mention this code is almost a copy of this guide : https://docs.expo.dev/guides/authentication/#dropbox
Note 2 : I’m at a point of my application where there are not much expo
dependencies so I’m not closed to the idea of using libraries that would work on standalone (non-expo) apps. In that case I would need an in-app browser module that exposes functions to retrieve redirect and response parameters, and to trigger callbacks on page load… something like that.