tuupola / slim-basic-auth

PSR-7 and PSR-15 HTTP Basic Authentication Middleware
MIT License
440 stars 66 forks source link

Enhancement: require auth only for specified HTTP method #30

Closed sivann closed 7 years ago

sivann commented 7 years ago

In addition to URI/path I think it would be very useful if there could be a way to require auth based on HTTP methods. E.g.: allow all GET and PUT requests to /api/items but require auth for POST and DELETE on /api/items

so $path could be like $path = ['GET'=>['path1','path2'], 'POST'=>..., ALL=>..], same for $passthrough

This can be done on the __invoke function of class implementing the AuthenticatorInterface by differentiating on method like so:

class CustomAuthenticator implements AuthenticatorInterface {
       public function __invoke(array $arguments) {
       ...
        $request = $this->app->getContainer()->get('request');
        $method = $request->getMethod();
        $uri = "/" . $request->getUri()->getPath();
        $uri = str_replace("//", "/", $uri);

        //always allow the following URL/METHOD combinations
        $allow = [
            'GET'=>['/api/hostids/[^/]+/keys'],
            'POST'=>[
                     '/api/hostids/[^/]+',
                     '/api/hostids/[^/]+/logs'
                     ],
        ];

        $allow_method = $allow[$method];
        foreach ($allow_method as $url_pattern) {
            if (preg_match('@^'.$url_pattern.'@', $uri)) {
                return true;
            }
        }

but I think an easier definition would be beneficial.

tuupola commented 7 years ago

You can write a custom rule for that. If a rule return true request will be authenticated. If false request will not be authenticated. Default rules are RequestPathRule and RequestMethodRule. What you are looking for is some kind of combination of those two.

sivann commented 7 years ago

Ah , thank you. I saw the rules implementation, seems very elegant. This is not just an auth module, it's also a "how to code" tutorial :-) You can perhaps add the rules feature to the README as I didn't think to read the code.

tuupola commented 7 years ago

Now that you reminded me about it. I should document how to use rules bit better.