I have an ASP.NET Core 2.2 API, a web app built in React and now building a React Native mobile app.
Everything is working nicely on the web app. I’m also able to obtain an access_token
and an id_token
from the React Native mobile app but when I call the API using the access_token
obtained, my API is rejecting it with 401
error.
Is there anything special I need to configure on Auth0 portal for my mobile app to work? In addition to my web app, I created a separate mobile app on the portal and I’m using its clientId
to make my calls. As I said, I’m able to call Auth0 and obtain my tokens just fine but my API is not accepting the access_token
.
I simply followed the article here for React Native but here’s what my code looks like in my mobile app:
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, Button } from 'react-native';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Auth0 from 'react-native-auth0';
import jwt_decode from 'jwt-decode';
// Actions
import * as myActions from '../../actions/my-actions';
// Utils
import { saveAccessToken } from '../../utils/authentication/authentication-utils';
const auth0 = new Auth0({ domain: 'mydomain.auth0.com', clientId: 'client_id_assigned_to_my_mobile_app' });
class Login extends Component {
constructor(props) {
super(props);
this._onLogin = this._onLogin.bind(this);
this._onLogout = this._onLogout.bind(this);
}
_onLogin = () => {
auth0.webAuth
.authorize({
scope: 'openid profile',
audience: 'identifier_for_my_api'
})
.then(credentials => {
// Store access token
saveAccessToken(credentials.accessToken)
// Set authenticated user indicator
this.props.actions.setIsAuthenticated(true);
// Decode the id JWT token
const decoded = jwt_decode(credentials.idToken);
})
.catch(error => console.log(error));
};
_onLogout = () => {
if (Platform.OS === 'android') {
// Remove token
} else {
auth0.webAuth
.clearSession({})
.then(success => {
// Remove token
})
.catch(error => console.log(error));
}
};
render() {
return (
<View style={styles.container}>
<Text>Let's log you in...</Text>
<Button onPress={this._onLogin} title="Log In" />
</View>
);
}
}
function mapStateToProps(state) {
return {
isAuthenticated: state.app.isAuthenticated
}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(myActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
},
header: {
fontSize: 20,
textAlign: 'center',
margin: 10
}
});