使用Auth0在JWT中包含user_metadata和app_metadata [英] Include user_metadata and app_metadata in JWT using Auth0

查看:137
本文介绍了使用Auth0在JWT中包含user_metadata和app_metadata的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 2和Auth0在我的Web应用程序上进行身份验证.我可以使用以下代码获取用户个人资料:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆