【问题标题】:Decode firebase/php-jwt in Angular 6在 Angular 6 中解码 firebase/php-jwt
【发布时间】:2019-01-17 00:58:41
【问题描述】:

我在我的 Backend Api(使用 Lumen) 中使用 firebase/php-jwt 来提供 Authentication Token。 我在前端使用 Angular 6

这是我从后台登录后的结果:-

{
"message": "Successfully Authenticated !",
"status": "Found",
"code": 200,
"data": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJsdW1lbi1qd3QiLCJzdWIiOjEsImlhdCI6MTUzMzgxNjc3OCwiZXhwIjoxNTMzODIwMzc4fQ.84BaTHYoWPEzNsZ6Qu0YK-VQelN0WQ0gcmUdXsxO7OA"
}

我的这个令牌的有效负载结构是:-

$payload = [
        'iss' => "lumen-jwt", // Issuer of the token
        'sub' => $user->user_id, // Subject of the token
        'iat' => time(), // Time when JWT was issued.
        'exp' => time() + (60*60) // Expiration time
    ];

所以,当我解码它时,我只需解码:-

JWT::encode($payload, env('JWT_SECRET')); // In environment file "JWT_SECRET={random_secret_code}"

所以,我有一个我正在使用的常量 JWT_SECRET

我的问题是令牌在哪些算法中生成?因为我没有 在 encode() 函数中指定任何算法?

现在在 Angular 中,我如何通过解码令牌来获取 user_id、过期时间和其他信息?

【问题讨论】:

    标签: angular jwt angular6 lumen php-jwt


    【解决方案1】:

    令牌使用HS256 算法签名,该算法可能配置为 PHP-JWT 中的默认算法。您只需将令牌粘贴到 https://jwt.io 在线调试器中即可获取该信息。

    标题如下所示:

    {
      "typ": "JWT",
      "alg": "HS256"
    }
    

    在 Angular 中,您可以使用包 jwt-decode:

    安装:npm install --save jwt-decode

    并像这样使用它:

    var decode = require('jwt-decode');
    
    var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJsdW1lbi1qd3QiLCJzdWIiOjEsImlhdCI6MTUzMzgxNjc3OCwiZXhwIjoxNTMzODIwMzc4fQ.84BaTHYoWPEzNsZ6Qu0YK-VQelN0WQ0gcmUdXsxO7OA"
    const tokenPayload = decode(token);
    
    console.log(tokenPayload.exp) // read the expiration time
    

    【讨论】:

    • 您的回答确实对我仅通过算法部分的理解帮助很大。感谢那。除了您的使用示例之外,这个stackoverflow.com/questions/48075688/… 帮助我获得了角度的正确用法,只是为了让您知道。
    猜你喜欢
    • 2017-05-27
    • 2021-11-17
    • 2017-11-11
    • 2017-04-11
    • 2022-10-31
    • 2016-05-24
    • 2019-02-21
    • 1970-01-01
    • 2018-08-14
    相关资源
    最近更新 更多