使用 Auth0 在 JWT 中包含 user_metadata 和 app_metadata

Pab*_*emé 3 authentication auth0 angular

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

auth0 = new auth0.WebAuth({
    domain: 'MY-DOMAIN',
    clientID: 'MY-CLIENT-ID',
    callbackURL: 'MY-CALLBACK',
    responseType: 'token id_token'
});
Run Code Online (Sandbox Code Playgroud)

登录:

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']);
      }
    });
}
Run Code Online (Sandbox Code Playgroud)

保存tokenlocalStorage获取配置文件:

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;
      }
    });
}
Run Code Online (Sandbox Code Playgroud)

所以这有效,但我得到的配置文件对象不包括 Auth0 网站上配置的 user_metadata 或 app_metadata 。我怎样才能包含它?

Jes*_*res 5

Deevz 的答案是正确的,接受它,以便将其标记为这样。不过,我想对此进行扩展。您必须向 auth0 客户端添加新规则。这是在“规则”部分中完成的。

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);
}
Run Code Online (Sandbox Code Playgroud)

我希望它有帮助。

  • 由于某种原因,我必须提供一个 url 作为唯一的命名空间才能正常工作。即 `var 命名空间 = 'https://unique-namespace.com/'` (3认同)