Reputation: 1554
I am using Angular 2 and Auth0 for authentication on my web app. I am able to get the user profile using the following code:
auth0 = new auth0.WebAuth({
domain: 'MY-DOMAIN',
clientID: 'MY-CLIENT-ID',
callbackURL: 'MY-CALLBACK',
responseType: 'token id_token'
});
Login:
public login(username: string, password: string): void {
this.auth0.client.login({
realm: 'Username-Password-Authentication',
username,
password
}, (err: any, authResult: any) => {
if (err) {
alert('Error: ' + err.description);
return;
}
if (authResult && authResult.idToken && authResult.accessToken) {
this.setUser(authResult); <--- Here is where I get the profile
this.router.navigate(['/home']);
}
});
}
Saving token
on localStorage
and getting the profile:
private setUser(authResult: any): void {
localStorage.setItem('access_token', authResult.accessToken);
localStorage.setItem('id_token', authResult.idToken);
this.auth0.client.userInfo(authResult.accessToken, (error: any, profile: any) => {
if (!error) {
localStorage.setItem('profile', JSON.stringify(profile));
this.userProfile = profile;
}
});
}
So this works, but the profile object I get doesn't include the user_metadata or the app_metadata configured on the Auth0 website. How can I include it?
Upvotes: 4
Views: 3450
Reputation: 153
Deevz answer is correct, accept it so it is marked as such. I would like to expand on it, however. You have to add a new rule to your auth0 client. This is done in the 'Rules' section.
function (user, context, callback) {
var namespace = 'unique-namespace';
context.idToken[namespace + 'app_metadata'] = user.app_metadata;
context.idToken[namespace + 'user_metadata'] = user.user_metadata;
context.accessToken[namespace + 'app_metadata'] = user.app_metadata;
context.accessToken[namespace + 'user_metadata'] = user.user_metadata;
callback(null, user, context);
}
I hope it helps.
Upvotes: 6
Reputation: 61
You could use an Auth0 Hook. Login to Auth0 and on the left side navigation pane choose "Hooks". Under "Client Credentials Exchange" create a new hook. In here you can add to the scopes that by default your app passes in to the Lock API. Adding the following line:
access_token.scope.push('user_profile');
I believe should include both user_metadata AND app_metadata.
You should be able to also specify this from the client itself without using a hook. If you check out this link it should show you some extra options you can specify with regards to the scope parameter. This sample looks particularly useful:
var options = { auth: {
params: {scope: 'openid email user_metadata app_metadata picture'}, }};
Upvotes: 4