Connect to your Silverstripe site in React Native with Oauth2

May 10, 2019, 11:09 AM

When developing a mobile app to connect to your Silverstripe web app the best way of doing this is using the Oauth2 standard. This allows you to grant limited access to a HTTP service from another application.

There is a React Native library that supports the Oauth protocol for react native made by Formidable Labs: https://github.com/FormidableLabs/react-native-app-auth

Include this in your react native project using npm:

npm install react-native-app-auth --save

 

In your Silverstripe project you will need to install an Oauth server. League's Oauth Server for PHP is a well built library. We need a wrapper for the library for silverstripe and I managed to get Ian Simpson's project working for me. https://github.com/IanSimpson/ss-oauth2-server

Install this project using composer

composer require iansimpson/ss-oauth2-server

Then you will need to follow the instructions in the readme to create an RSA key pair. Remember to store the keys outside of your web root.

If you have the CMS installed, once you have dev/build you will see the Oauth options in your site settings in the CMS backend.

Create a scope called "test" for testing.

Create an Oauth client for your app.

The redirect will be your React Native app's APP ID with :/oauthredirect on the end.

 

Make a note of the client identifier and client secret, you will need to put these in your app's auth config.

Set up your connection parameters

const config = {
issuer: 'https://192.168.0.10/techdesk/oauth/authorize',
serviceConfiguration: {
authorizationEndpoint: 'https://192.168.0.10/techdesk/oauth/authorize',
tokenEndpoint: 'https://192.168.0.10/techdesk/oauth/accessToken'
},
clientId: 'a45886be97768465ac241ee6bb26761f',
clientSecret: '18ffb3c0a5bc3c67a5b00551230efc62925ccf18377c01f1403a948bfac1a3e1',
redirectUrl: 'com.yourappname:/oauthredirect',
scopes: ['test'],
dangerouslyAllowInsecureHttpRequests: true
};


try {
const result = await authorize(config);
// result includes accessToken, accessTokenExpirationDate and refreshToken
console.log(result);
} catch (error) {
console.log(error);
}

NOTES:

  • You will have to add the "serviceConfiguration" config object as the Silverstripe Oauth wrapper doesn't support the OIDC discovery protocol.
  • You have to use HTTPS to connect.
  • If you are testing on your local machine with a self signed certificate you will get network errors unless you add the "dangerouslyAllowInsecureHttpRequests" parameter. Remember to remove this on production!
  • Replace all IP addresses with the address of your local dev machine

When you fire the Oauth connection request if all is well you should be redirected to the login page of your Silverstripe app, and once logged in you will see the Oauth token dumped into the console!