使用 slimframework 读取令牌 [英] Reading token with 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 SlimSlim();
$app->add(new SlimMiddlewareContentTypes());
$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();
- 如何检查
/user
路径下的token?发出/user
请求我正在发送带有Authorization:Bearer eHrR....
的标头 - 只是为了清除 - 那种身份验证(登录名和密码)和 OAuth 是一样的吗?
- How to check token in
/user
path? Making/user
request I'm sending header withAuthorization:Bearer eHrR....
- And just for clearing - is that kind of auth (login and password) and OAuth the same?
推荐答案
您可以使用 JSON网络令牌认证中间件.使用 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}]
然后将中间件添加到 Slim 应用程序中.当发出请求时,中间件会尝试验证和解码令牌.如果未找到令牌,服务器将以 401 Unauthorized
响应.如果令牌存在但在验证和解码时出错,服务器将响应 400 Bad Request
.
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 SlimSlim();
$app->add(new SlimMiddlewareJwtAuthentication([
"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屋!