Generate jwt with user information
Asked Answered
F

1

1

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"]);
    }
]));

Route

$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');

});
Fonzie answered 28/9, 2020 at 18:43 Comment(1)
How do you pass the login details to the route?Saxecoburggotha
N
1

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

JWT::decode($token, $key, array(‘HS256’));
Nauseating answered 28/9, 2020 at 18:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.