使用slimframework读取令牌 [英] Reading token with slimframework

查看:76
本文介绍了使用slimframework读取令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SlimFramework和JWT处理具有登录名和密码的基于令牌的身份验证。

I'm using SlimFramework and JWT to handle token based authentication with login and password.

我设法登录并发送令牌作为响应。

I managed to login and send token in response.

这是我的代码:

<?php
require_once("vendor/autoload.php");

$app = new \Slim\Slim();
$app->add(new \Slim\Middleware\ContentTypes());

$app->post('/auth/login', function () use ($app) {
    $params = $app->request()->getBody();
    if ($params['email'] == "login" && $params['password'] == "password") {
        $key = "example_key";
        $token = array(
            "id" => "1",
            "exp" => time() + (60 * 60 * 24)
        );
        $jwt = JWT::encode($token, $key);
        $app->response->headers->set('Content-Type', 'application/json');
        echo json_encode(array("token" => $jwt));
    }
});

$app->get("/user", function () {
    echo "ok";
});
$app->run();




  1. 如何在 / user <中检查令牌/ code>路径?
    发出 / user 请求我正在发送带有 Authorization:Bearer eHrR .....
  2. 只是为了清除-这种身份验证(登录名和密码)和OAuth是否相同?

  1. How to check token in /user path? Making /user request I'm sending header with Authorization:Bearer eHrR....
  2. And just for clearing - is that kind of auth (login and password) and OAuth the same?


推荐答案

您可以使用 JSON Web令牌认证中间件。使用composer安装最新版本。

You can use JSON Web Token Authentication middleware. Install latest version using composer.

$ composer require tuupola/slim-jwt-auth

还将以下内容添加到 .htaccess文件。否则,PHP将无法访问 Authorization:Bearer 标头。

Also add the following to the .htaccess file. Otherwise PHP wont have access to the Authorization: Bearer header.

RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

然后将中间件添加到苗条的应用程序。发出请求时,中间件尝试验证和解码令牌。如果未找到令牌,服务器将响应 401 Unauthorized 。如果令牌存在,但在验证和解码时出错,则服务器将响应 400错误请求

Then add the middleware to the Slim application. When request is made middleware tries to validate and decode the token. If token is not found server will response with 401 Unauthorized. If token exists but there is an error when validating and decoding it server will response with 400 Bad Request.

回调函数中间件将令牌的内容存储到 $ app-> jwt

In the callback function middleware stores the content of token to $app->jwt. You can access this later in other routes.

$app = new \Slim\Slim();

$app->add(new \Slim\Middleware\JwtAuthentication([
    "secret" => "your_example_key",
    "callback" => function ($options) use ($app) {
        $app->jwt = $options["decoded"];
    }
]));

$app->get("/user", function () {
    print_r($app->jwt);
});

$app->run();

这篇关于使用slimframework读取令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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