如何在中间件超薄的PHP框架回应 [英] How to respond in Middleware Slim PHP Framework

查看:164
本文介绍了如何在中间件超薄的PHP框架回应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了身份验证的中间件到REST API。我的API使用超薄的PHP框架,该框架的情况下,提供了强大的功能来构建API创建的。这其中一个特点是中间件。结果
我需要检查凭据在中间件和一个错误(HTTP code。与JSON的描述),以响应用户。结果
但不幸的是修身框架给了我,每当我试图阻止,并与HTTP code反应异常。

I am creating middleware for auth into REST API. My API is created using Slim PHP Framework ,which in case provide great features to build APIs. One of this feature is Middleware.
I need to check credentials in Middleware and respond with an error (HTTP code with JSON descriptions) to the user.
But unfortunatly Slim Framework gives me an exception whenever I try to halt and respond with the HTTP code.

<?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 方式使用超薄框架方法的 $ APP->停止($code,$响应);

respondWithHttpStatus method uses slim framework method $app->halt($code, $response);

在当我尝试执行这个方法,我得到从异常这种情况下

In this case when I try to execute this method I get an Exception from

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 code和描述错误的原因JSON消息不对劲响应。结果
也许这是更好地遵循另一种方式。结果
请建议。

How to deal with this problem.
My goal is to control user credentials in middleware and if it is something wrong respond with the appropriate HTTP code and JSON message describing the reason of the error.
Maybe it is better to follow another way.
Please suggest.

一个可能的解决方法

   $app->response->setStatus(400);
   $app->response->headers->set('Content-Type', 'application/json');
   print Response::respondWithHttpStatus($app,400,false);

和响应函数

公共静态功能basicRespond($应用程序,$code,$消息,$停止){

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;
    }
}

有关我的需求很相称,还抛出一个异常可能是另一种解决方案,但在我来说,我并不需要继续,只设置标题,code,不叫旁边 - 为我工作

For my needs suits well, also throwing an exception can be another solution but in my case I don't need to continue, just setting header, code and don't call next - works for me.

推荐答案

您不能使用停止中间件:

<一个href=\"http://stackoverflow.com/a/10201595/2970321\">http://stackoverflow.com/a/10201595/2970321

暂停应该仅路由回调的上下文中调用

Halt should only be invoked within the context of a route callback.

相反,您可以手动生成一个 400 响应使用PHP的一起退出

Instead, you could manually generate a 400 response using PHP's header along with exit:

header("HTTP/1.1 400 Access denied");
exit;

或者

您可以定义一个新的类型的异常:

Alternatively,

you could define a new type of Exception:

class AuthException extends Exception {
    public function __construct() {
        $message = 'You must authenticate to access this resource.';
        $code = 400;
    }
}

在你的错误

抓住这个路线:

$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 当授权予以否认:

And throw an AuthException when authorization is to be denied:

throw new AuthException();

这实质上是它是如何在修身验证

This is essentially how it is done in Slim-Auth.

这篇关于如何在中间件超薄的PHP框架回应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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