Slim PHP Framework中间件自定义URL过滤器

I am creating API using Slim Framework. I need to filter requests required authentication and route them to the specific auth handler. Or it would be better to say that I need to filter URI that don't require auth (public information).

I have created following middleware skileton

class TokenAuth extends \Slim\Middleware {
    private $auth;
    public function __construct($userEmail,$accesToken,$appSecret) {

    }

    /**
     * Deny Access
     *
     */
    public function deny_access() {
        $res = $this->app->response();
        $res->status(401);
    }


    public function authenticate($token) {
        ....
    }

    /**
     * Call
     *
     */
    public function call() {
        //Get the token sent from jquery

        $tokenAuth = $app->request->headers->get('Authorization');

        //Check if our token is valid
        if ($this->authenticate($tokenAuth)) {
        ....
        } else {
            $this->deny_access();
        }
    }

}

In this case I cannot access any URI without token, how to solve this problem, allowing access to the public resources.
I would be grateful for any help. Thx in advance.

2个回答

You have mainly two ways of doing it :

Global middleware

One way consist in adding an OAuth middleware to your API so you can check if user is authenticated or not and setup a flag, then inside each route you can do a simple check if user is authenticated or not.

<?php
$app = new \Slim\Slim();
$app-authenticated = false;
$app->add(new MyOAuthMiddleware());

Then your MyOAuthMiddleware :

<?php
 class MyOAuthMiddleware extends \Slim\Middleware {
  public function call() {
   //Do your OAUTH check stuff here
   $this->app-authenticated = true;
  }
}

Now you can check in all your routes :

<?php
$app->get('/hello/:name', function ($name) {
   $app = \Slim\Slim::getInstance();
   if($app->authenticated === true){
    echo "Hello, $name";
   } else {
    echo "You need to login";
   }
});

Specific route middleware

You can follow Slim documentation and choose to add your Middleware directly on each declaration :

<?php
$authenticateForRole = function ( $role = 'member' ) {
    return function () use ( $role ) {
        $user = User::fetchFromDatabaseSomehow();
        if ( $user->belongsToRole($role) === false ) {
            $app = \Slim\Slim::getInstance();
            $app->flash('error', 'Login required');
            $app->redirect('/login');
        }
    };
};
$app = new \Slim\Slim();
$app->get('/foo', $authenticateForRole('admin'), function () {
    //Display admin control panel
});
dongqiuge5435
dongqiuge5435 是的,最终可以使用$ app-> request访问当前请求,这是Slim \ Http \ Request Object并进行检查。
5 年多之前 回复
dongou4052
dongou4052 很好的答案,如果我将检查中间件中的URI,如果它不需要登录,只需拨打下一个怎么办?
5 年多之前 回复



此处的常见策略是使用规则实施防火墙。 </ p>

一个非常简单的防火墙可能会忽略公共资产(即以.jpg,.png,.css,.js等结尾的任何内容)。 规则通常只是正则表达式。</ p>

示例防火墙配置可能看起来像(注意规则的应用顺序也很重要)。</ p>

 <  code> firewalls:
#公共资产,任何人都可以看到
assets:
表达式:\。(js | css)$
auth:false

#一切异常登录需要auth
secure:
表达式:^(?!login $)
auth:true

#其他所有内容都通过
public:
表达式:^ /
auth:false
</ code> </ pre>

您是否有框架解析定义并迭代规则。 从那里,您可以决定如何处理路由。</ p>
</ div>

展开原文

原文

A common strategy here is to implement a firewall with rules.

A very simple firewall might ignore public assets (i.e., anything ending in .jpg, .png, .css, .js, etc.). Rules are commonly simply regular expressions.

An example firewall configuration might look like (note the order the rules are applied are also important).

firewalls:
    # Public assets, anyone can see
    assets:
        expression: \.(js|css)$
        auth: false

    # Everything exception login requires auth
    secure:
        expression: ^(?!login$)
        auth: true

    # Everything else gets through
    public:
        expression: ^/
        auth: false

Have you framework parse the definition and iterate over the rules. From there, you can decide how to handle the routing.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐