如何从 auth0 中的访问令牌中获取 jwt 令牌

Posted

技术标签:

【中文标题】如何从 auth0 中的访问令牌中获取 jwt 令牌【英文标题】:how to get jwt token from access token in auth0 【发布时间】:2018-01-13 03:22:56 【问题描述】:

我正在开发 angular2-nodejs-mongodb 单页应用程序。并使用 auth0 安全性。

我从 angular2 项目中获得了 access_token。但它不是 jwt_token。主要问题是 node.js 项目需要 jwt_token 像 Authorization : Bearer My_Token。下面附上图片。

角度图像:获取 access_token

postman:send 要求 auth0 获取 jwt_token

邮递员:尝试访问我的 nodejs 应用程序

其实我不明白,如何将角度访问令牌转换为 node.js jwt_token

【问题讨论】:

在这里分享您的代码。 刚刚从 git angular2 创建项目:github.com/auth0-samples/auth0-angular-samples nodejs : github.com/auth0-samples/auth0-express-api-samples 【参考方案1】:

假设我在互联网上找到了这个解决方案

实际上是从私人仓库中复制了一些代码)

const createClient = () => createAuth0Client(
  domain: AUTH0_DOMAIN,
  client_id: AUTH0_ID,
  redirect_uri: window.location.origin,
);

...

export class AuthService 

  constructor(
    public sessionService: SessionService,
    public alertService: AlertService,
    public userService: UserService,
  ) 
    makeObservable(this, 
      sessionService: observable,
      alertService: observable,
      userService: observable,
      authPopup: action.bound,
      authRedirect: action.bound,
      _handleNewToken: action.bound,
      init: action.bound,
    );
    this.init();
  

  async _handleNewToken(auth0: Auth0Client) 
    const 
      _raw: jwt,
      nickname,
      picture,
      email,
     = await auth0.getIdTokenClaims();
    nickname && this.userService.setNickname(nickname);
    picture && this.userService.setPicture(picture);
    email && this.userService.setEmail(email);
    this.sessionService.setSessionId(jwt);
    //                               ^^^
  

  async authPopup() 
    let token: string | false = false;
    try 
      const auth0 = await createClient();
      await auth0.loginWithPopup();
      await this._handleNewToken(auth0);
      this.alertService.push('Signed in successfully');
     catch (e) 
      console.log(e);
      this.alertService.push('Authorization failed');
     finally 
      return token;
    
  

  async authRedirect() 
    try 
      const auth0 = await createClient();
      await auth0.loginWithRedirect();
      await sleep(5_000);
     catch(e) 
      console.log(e);
      this.alertService.push('Authorization failed');
    
  

  async init() 
    try 
      const auth0 = await createClient();
      await auth0.handleRedirectCallback();
      await this._handleNewToken(auth0);
      this.alertService.push('Signed in successfully');
     catch (e) 
      console.log(e);
    
  

;

...

const handleButtonClick = () => 
        await authService.authRedirect();
        ...
;

【讨论】:

以上是关于如何从 auth0 中的访问令牌中获取 jwt 令牌的主要内容,如果未能解决你的问题,请参考以下文章