使用 Auth0 在 JWT 中包含 user_metadata 和 app_metadata [英] Include user_metadata and app_metadata in JWT using Auth0
问题描述
我在我的网络应用程序上使用 Angular 2 和 Auth0 进行身份验证.我可以使用以下代码获取用户个人资料:
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'
});
登录:
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']);
}
});
}
在 localStorage
上保存 token
并获取配置文件:
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;
}
});
}
所以这可行,但我得到的配置文件对象不包括在 Auth0 网站上配置的 user_metadata 或 app_metadata.我怎样才能包含它?
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?
推荐答案
Deevz 的回答是正确的,接受它所以它被标记为这样.但是,我想扩展它.您必须向 auth0 客户端添加新规则.这是在规则"部分完成的.
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);
}
希望能帮到你.
这篇关于使用 Auth0 在 JWT 中包含 user_metadata 和 app_metadata的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!