如何在 Middleware Slim PHP Framework 中响应
How to respond in Middleware Slim PHP Framework
我正在为 REST 中的身份验证创建中间件 API。我的 API 是使用 Slim PHP Framework 创建的,它可以为构建 API 提供强大的功能。这些功能之一是中间件。
我需要检查中间件中的凭据并向用户响应错误(带有 JSON 描述的 HTTP 代码)。
但不幸的是,每当我尝试停止并使用 HTTP 代码进行响应时,Slim Framework 都会给我一个异常。
<?php
require_once __DIR__.'/../Slim/Middleware.php';
class TokenAuth extends \Slim\Middleware {
private $auth;
const SECURED_URI_REGEX = "/^\/v\d\/store\/(orders|users|payment).*/";
const TOKEN_PARAMETER = "token";
const USER_EMAIL_PARAMETER = "user_email";
public static $credentialsArray = array(TokenAuth::TOKEN_PARAMETER,TokenAuth::USER_EMAIL_PARAMETER);
public function __construct() {
}
public function deny_access() {
print Response::respondWithHttpStatus($app,401,true);
}
public function call() {
$app = $this->app;
$uri = $app->request->getResourceUri();
if (preg_match(TokenAuth::SECURED_URI_REGEX, $uri)) {
$tokenAuth = $app->request->headers->get('Authorization');
if(isset($tokenAuth)) {
$parsedCredentials = TokenAuth::parseAndValidateCredentials($tokenAuth);
if (!$parsedCredentials) {
Response::respondWithHttpStatus($app,401,true);
}
else {
$auth = new Authenticator($parsedCredentials[TokenAuth::USER_EMAIL_PARAMETER],$app);
print $auth->userHasToken();
}
}
else {
Response::respondWithHttpStatus($app,400,true);
}
}
else {
$this->next->call();
}
}
respondWithHttpStatus 方法使用 slim 框架方法 $app->halt($code, $response);
在这种情况下,当我尝试执行此方法时,我从
得到了一个异常
Slim Framework
The application could not run because of the following error:
Details
Type: Slim\Exception\Stop
File: /var/www/api/Slim/Slim.php
Line: 1022
如何处理这个问题。
我的目标是控制中间件中的用户凭据,如果出现问题,则使用适当的 HTTP 代码和描述错误原因的 JSON 消息进行响应。
也许换一种方式更好。
请提出建议。
一种可能的解决方法
$app->response->setStatus(400);
$app->response->headers->set('Content-Type', 'application/json');
print Response::respondWithHttpStatus($app,400,false);
以及响应函数
public static function basicRespond($app,$code,$message,$halt) {
if(!isset($message) || empty($message)) {
$message = Response::$RESPONSE_MAP[$code];
}
$response = json_encode($message);
if($halt===true) {
$app->halt($code, $response);
}
else {
return $response;
}
}
对于我的需求很合适,抛出异常也可以是另一种解决方案,但在我的情况下,我不需要继续,只需设置 header,代码并且不调用 next - 有效对我来说。
您不能在中间件中使用 halt
:
Halt should only be invoked within the context of a route callback.
相反,您可以使用 PHP 的 header
和 exit
:
手动生成 400
响应
header("HTTP/1.1 400 Access denied");
exit;
或者,
您可以定义一种新的异常类型:
class AuthException extends Exception {
public function __construct() {
$message = 'You must authenticate to access this resource.';
$code = 400;
}
}
在你的 error
路线中抓住这个:
$app->error(function (\Exception $e) use ($app) {
// Example of handling Auth Exceptions
if ($e instanceof AuthException) {
$app->response->setStatus($e->getCode());
$app->response->setBody($e->getMessage());
}
});
并在拒绝授权时抛出 AuthException
:
throw new AuthException();
这基本上就是 Slim-Auth 中的做法。
我正在为 REST 中的身份验证创建中间件 API。我的 API 是使用 Slim PHP Framework 创建的,它可以为构建 API 提供强大的功能。这些功能之一是中间件。
我需要检查中间件中的凭据并向用户响应错误(带有 JSON 描述的 HTTP 代码)。
但不幸的是,每当我尝试停止并使用 HTTP 代码进行响应时,Slim Framework 都会给我一个异常。
<?php
require_once __DIR__.'/../Slim/Middleware.php';
class TokenAuth extends \Slim\Middleware {
private $auth;
const SECURED_URI_REGEX = "/^\/v\d\/store\/(orders|users|payment).*/";
const TOKEN_PARAMETER = "token";
const USER_EMAIL_PARAMETER = "user_email";
public static $credentialsArray = array(TokenAuth::TOKEN_PARAMETER,TokenAuth::USER_EMAIL_PARAMETER);
public function __construct() {
}
public function deny_access() {
print Response::respondWithHttpStatus($app,401,true);
}
public function call() {
$app = $this->app;
$uri = $app->request->getResourceUri();
if (preg_match(TokenAuth::SECURED_URI_REGEX, $uri)) {
$tokenAuth = $app->request->headers->get('Authorization');
if(isset($tokenAuth)) {
$parsedCredentials = TokenAuth::parseAndValidateCredentials($tokenAuth);
if (!$parsedCredentials) {
Response::respondWithHttpStatus($app,401,true);
}
else {
$auth = new Authenticator($parsedCredentials[TokenAuth::USER_EMAIL_PARAMETER],$app);
print $auth->userHasToken();
}
}
else {
Response::respondWithHttpStatus($app,400,true);
}
}
else {
$this->next->call();
}
}
respondWithHttpStatus 方法使用 slim 框架方法 $app->halt($code, $response);
在这种情况下,当我尝试执行此方法时,我从
得到了一个异常Slim Framework
The application could not run because of the following error:
Details
Type: Slim\Exception\Stop
File: /var/www/api/Slim/Slim.php
Line: 1022
如何处理这个问题。
我的目标是控制中间件中的用户凭据,如果出现问题,则使用适当的 HTTP 代码和描述错误原因的 JSON 消息进行响应。
也许换一种方式更好。
请提出建议。
一种可能的解决方法
$app->response->setStatus(400);
$app->response->headers->set('Content-Type', 'application/json');
print Response::respondWithHttpStatus($app,400,false);
以及响应函数
public static function basicRespond($app,$code,$message,$halt) {
if(!isset($message) || empty($message)) {
$message = Response::$RESPONSE_MAP[$code];
}
$response = json_encode($message);
if($halt===true) {
$app->halt($code, $response);
}
else {
return $response;
}
}
对于我的需求很合适,抛出异常也可以是另一种解决方案,但在我的情况下,我不需要继续,只需设置 header,代码并且不调用 next - 有效对我来说。
您不能在中间件中使用 halt
:
Halt should only be invoked within the context of a route callback.
相反,您可以使用 PHP 的 header
和 exit
:
400
响应
header("HTTP/1.1 400 Access denied");
exit;
或者,
您可以定义一种新的异常类型:
class AuthException extends Exception {
public function __construct() {
$message = 'You must authenticate to access this resource.';
$code = 400;
}
}
在你的 error
路线中抓住这个:
$app->error(function (\Exception $e) use ($app) {
// Example of handling Auth Exceptions
if ($e instanceof AuthException) {
$app->response->setStatus($e->getCode());
$app->response->setBody($e->getMessage());
}
});
并在拒绝授权时抛出 AuthException
:
throw new AuthException();
这基本上就是 Slim-Auth 中的做法。