To use Apple Authentication with Auth0, you must perform a token exchange. This involves:
- Using
appleAuth.performRequest to initiate the login and request scopes like FULL_NAME and EMAIL. - Verifying the credential state using
appleAuth.getCredentialStateForUser. - Sending a
POST request to your Auth0 domain's /oauth/token endpoint using the urn:ietf:params:oauth:grant-type:token-exchange grant type.
Required parameters for the Auth0 token exchange request:
grant_type: Must be urn:ietf:params:oauth:grant-type:token-exchange.subject_token_type: Must be http://auth0.com/oauth/token-type/apple-authz-code.subject_token: The authorizationCode obtained from the appleAuth.performRequest response.client_id: Your Auth0 Client ID.audience: Your Auth0 Audience.user_profile: A JSON string containing the user's name and email.
import { appleAuth } from '@invertase/react-native-apple-authentication';
import axios from 'axios';
import {
auth0Client,
auth0Domain,
auth0Audience
} from '../constants/constants';
export default async function AppleAuthentication() {
return new Promise(async (resolve, reject) => {
const appleAuthRequestResponse = await appleAuth.performRequest({
nonceEnabled: false,
requestedOperation: appleAuth.Operation.LOGIN,
requestedScopes: [appleAuth.Scope.FULL_NAME, appleAuth.Scope.EMAIL]
});
const credentialState = await appleAuth.getCredentialStateForUser(
appleAuthRequestResponse.user
);
if (credentialState === appleAuth.State.AUTHORIZED) {
const {
fullName,
authorizationCode,
email
} = appleAuthRequestResponse,
{ familyName, givenName } = fullName;
await axios({
url: `https://${auth0Domain}/oauth/token`,
method: 'POST',
data: {
grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
subject_token_type: 'http://auth0.com/oauth/token-type/apple-authz-code',
scope: 'read:appointments openid profile email email_verified',
audience: auth0Audience,
subject_token: authorizationCode,
client_id: auth0Client,
user_profile: JSON.stringify({
name: {
firstName: givenName,
lastName: familyName
},
email: email
})
}
})
.then(async (_auth0Response) => {
resolve({
message: 'success',
..._auth0Response,
first_name: givenName,
last_name: familyName
});
})
.catch((_auth0Error) => {
reject({ error: true, message: 'error', detailedInformation: _auth0Error });
});
}
});
}