Merge pull request #98 from byCedric/feat/auth0

feat: add auth0 auth session example
This commit is contained in:
Evan Bacon
2020-02-20 12:35:40 -08:00
committed by GitHub
6 changed files with 162 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

97
with-auth0/App.js Normal file
View File

@@ -0,0 +1,97 @@
import React from 'react';
import { Alert, Button, StyleSheet, Text, View } from 'react-native';
import { AuthSession } from 'expo';
import jwtDecode from 'jwt-decode';
// You need to swap out the Auth0 client id and domain with the one from your Auth0 client.
// In your Auth0 client, you need to also add a url to your authorized redirect urls.
//
// For this application, I added https://auth.expo.io/@arielweinberger/with-auth0 because I am
// signed in as the "arielweinberger" account on Expo and the name/slug for this app is "with-auth0".
//
// You can open this app in the Expo client and check your logs to find out your redirect URL.
const auth0ClientId = '';
const auth0Domain = 'https://arielweinberger.eu.auth0.com';
export default class App extends React.Component {
state = {
name: null,
};
login = async () => {
// Retrieve the redirect URL, add this to the callback URL list
// of your Auth0 application.
const redirectUrl = AuthSession.getRedirectUrl();
console.log(`Redirect URL: ${redirectUrl}`);
// Structure the auth parameters and URL
const queryParams = toQueryString({
client_id: auth0ClientId,
redirect_uri: redirectUrl,
response_type: 'id_token', // id_token will return a JWT token
scope: 'openid profile', // retrieve the user's profile
nonce: 'nonce', // ideally, this will be a random value
});
const authUrl = `${auth0Domain}/authorize` + queryParams;
// Perform the authentication
const response = await AuthSession.startAsync({ authUrl });
console.log('Authentication response', response);
if (response.type === 'success') {
this.handleResponse(response.params);
}
};
handleResponse = (response) => {
if (response.error) {
Alert('Authentication error', response.error_description || 'something went wrong');
return;
}
// Retrieve the JWT token and decode it
const jwtToken = response.id_token;
const decoded = jwtDecode(jwtToken);
const { name } = decoded;
this.setState({ name });
};
render() {
const { name } = this.state;
return (
<View style={styles.container}>
{name
? <Text style={styles.title}>You are logged in, {name}!</Text>
: <Button title="Log in with Auth0" onPress={this.login} />
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
textAlign: 'center',
marginTop: 40,
},
});
/**
* Converts an object to a query string.
*/
function toQueryString(params) {
return '?' + Object.entries(params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
}

35
with-auth0/README.md Normal file
View File

@@ -0,0 +1,35 @@
# Auth0 Example
<p>
<!-- iOS -->
<img alt="Supports Expo iOS" longdesc="Supports Expo iOS" src="https://img.shields.io/badge/iOS-4630EB.svg?style=flat-square&logo=APPLE&labelColor=999999&logoColor=fff" />
<!-- Android -->
<img alt="Supports Expo Android" longdesc="Supports Expo Android" src="https://img.shields.io/badge/Android-4630EB.svg?style=flat-square&logo=ANDROID&labelColor=A4C639&logoColor=fff" />
</p>
## 🚀 How to use
- Install with `yarn` or `npm install`.
- Create your own app on [Auth0](https://auth0.com).
- Add the AppSession's auth URL to `Allowed Callback URLs` on Auth0.
- Open `App.js` and replace `auth0ClientId` and `auth0Domain` with your app settings.
- Run [`expo start`](https://docs.expo.io/versions/latest/workflow/expo-cli/), try it out.
#### AuthSession callback URL
The AuthSession helps you with browser authentication, without the need of an additional server or website. To use this with Auth0 authentication flows, we need to tell Auth0 that the callback URLs are allowed.
Each Expo user has it's own URL for different projects, the basic structure of this URL is `https://auth.expo.io/@your-username/your-expo-app-slug`. If you are signed in as `awesome-ppl`, and your app is called `meme-explorer`, your URL looks like `https://auth.expo.io/@awesome-ppl/meme-explorer`.
> [Read more about AuthSession here](https://docs.expo.io/versions/latest/sdk/auth-session/)
#### Auth0 app settings
Both the `auth0ClientId` and `auth0Domain` needs to match your Auth0 app settings.
![Application Settings](.gh-assets/auth0-app-settings.jpg)
## 📝 Notes
- [Expo AuthSession docs](https://docs.expo.io/versions/latest/sdk/auth-session/)
- [Auth0 React/SPA quickstart guide](https://auth0.com/docs/quickstart/spa/react)

12
with-auth0/app.json Normal file
View File

@@ -0,0 +1,12 @@
{
"expo": {
"name": "with-auth0",
"version": "1.0.0",
"icon": "https://github.com/expo/expo/blob/master/templates/expo-template-blank/assets/icon.png?raw=true",
"splash": {
"image": "https://github.com/expo/expo/blob/master/templates/expo-template-blank/assets/splash.png?raw=true",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
}
}
}

View File

@@ -0,0 +1,6 @@
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
};
};

12
with-auth0/package.json Normal file
View File

@@ -0,0 +1,12 @@
{
"dependencies": {
"expo": "36.0.0",
"jwt-decode": "2.2.0",
"react": "16.9.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz"
},
"devDependencies": {
"@babel/core": "7.0.0",
"babel-preset-expo": "8.0.0"
}
}