使用用户信息生成 jwt [英] Generate jwt with user information

查看:36
本文介绍了使用用户信息生成 jwt的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Slim/PHP 中的 HttpBasicAuthentication 来保护对我的/login"的访问路由,在验证访问后,将创建一个 JWT 以提供对所有路由的访问权限.所以我想用来自 DB 的用户配置文件信息生成一个自定义 jwt,但我无法获取用户的信息......所有参数都是空的.怎么解决?

I using HttpBasicAuthentication from Slim/PHP to protect access to my "/login" route, after validate access a JWT will be create to give access to all routes. So I wanna to generate a custom jwt with user profile information from DB but I cannot get user’s information… all arguments are empty. How to solve that?

$app->add(new \Tuupola\Middleware\HttpBasicAuthentication([ 
    "path" => "/login",
    "realm" => "Protected",
    "authenticator" => new LoginAuthenticator(),
    "error" => function ($response, $arguments) {
        $data = [];
        $data["status"] = "error";
        $data["message"] = $arguments["message"];

        $body = $response->getBody();
        $body->write(json_encode($data, JSON_UNESCAPED_SLASHES));

        return $response->withBody($body);
    },    
    "before" => function ($request, $arguments) {
        return $request->withAttribute("user", $arguments["user"]);
    }
]));

路线

$app->get('/login', function (Request $request, Response $response) use ($app) {

    $params = (object) $request->getParams()
    $key = $this->get("secretkey");

    $token = array(
        "user" => $params->user,
        "email" => $params->email,
        "age" => $params->age
    );

    $jwt = JWT::encode($token, $key);  

    return $response->withJson(["jwt" => $jwt], 200)
        ->withHeader('Content-type', 'application/json');

});

推荐答案

如果你有 $token , $key, algorithm ,你可以用代码检索payload

if you have $token , $key, algorithm , you can retrieve payload with code down

JWT::decode($token, $key, array(‘HS256’));

这篇关于使用用户信息生成 jwt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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