Code Monkey home page Code Monkey logo

slim-basic-auth's Introduction

PSR-7 and PSR-15 Basic Auth Middleware

This middleware implements HTTP Basic Authentication. It was originally developed for Slim but can be used with all frameworks using PSR-7 or PSR-15 style middlewares. It has been tested with Slim Framework and Zend Expressive.

Latest Version Packagist Software License Build Status Coverage

Heads up! You are reading documentation for 3.x branch which is PHP 7.1 and up only. If you are using older version of PHP see the 2.x branch. These two branches are not backwards compatible, see UPGRADING for instructions how to upgrade.

Install

Install latest version using composer.

$ composer require tuupola/slim-basic-auth

Usage

Configuration options are passed as an array. Only mandatory parameter is users. This is an array where you pass one or more "username" => "password" combinations. Username is the key and password is the value.

$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ]
]));

Same with Zend Expressive.

$app = Zend\Expressive\AppFactory::create();

$app->pipe(new Tuupola\Middleware\HttpBasicAuthentication([
    "users" => [
        "root" => "t00r",
        "user" => "passw0rd"
    ]
]));

Rest of the examples assume you are using Slim Framework.

Cleartext passwords are only good for quick testing. You probably want to use hashed passwords. Hashed password can be generated with htpasswd command line tool or password_hash() PHP function

$ htpasswd -nbBC 10 root t00r
root:$2y$10$1lwCIlqktFZwEBIppL4ak.I1AHxjoKy9stLnbedwVMrt92aGz82.O
$ htpasswd -nbBC 10 somebody passw0rd
somebody:$2y$10$6/vGXuMUoRlJUeDN.bUWduge4GhQbgPkm6pfyGxwgEWT0vEkHKBUW
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "users" => [
        "root" => '$2y$10$1lwCIlqktFZwEBIppL4ak.I1AHxjoKy9stLnbedwVMrt92aGz82.O',
        "somebody" => '$2y$10$6/vGXuMUoRlJUeDN.bUWduge4GhQbgPkm6pfyGxwgEWT0vEkHKBUW'
    ]
]));

Even if you are using hashed passwords it is not the best idea to store credentials in the code. Instead you could store them in environment or external file which is not committed to GitHub.

$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "users" => [
        "admin" => getenv("ADMIN_PASSWORD")
    ]
]));

Optional parameters

Path

The optional path parameter allows you to specify the protected part of your website. It can be either a string or an array. You do not need to specify each URL. Instead think of path setting as a folder. In the example below everything starting with /api will be authenticated.

$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/api", /* or ["/admin", "/api"] */
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ]
]));

Ignore

With optional ignore parameter you can make exceptions to path parameter. In the example below everything starting with /api and /admin will be authenticated with the exception of /api/token and /admin/ping which will not be authenticated.

$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => ["/api", "/admin"],
    "ignore" => ["/api/token", "/admin/ping"],
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ]
]));

Before

Before function is called only when authentication succeeds but before the next incoming middleware is called. You can use this to alter the request before passing it to the next incoming middleware in the stack. If it returns anything else than \Psr\Http\Message\RequestInterface the return value will be ignored.

$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ],
    "before" => function ($request, $arguments) {
        return $request->withAttribute("user", $arguments["user"]);
    }
]));

After

After function is called only when authentication succeeds and after the incoming middleware stack has been called. You can use this to alter the response before passing it next outgoing middleware in the stack. If it returns anything else than \Psr\Http\Message\ResponseInterface the return value will be ignored.

$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ],
    "after" => function ($response, $arguments) {
        return $response->withHeader("X-Brawndo", "plants crave");
    }
]));

Security

Basic authentication transmits credentials in clear text. For this reason HTTPS should always be used together with basic authentication. If the middleware detects insecure usage over HTTP it will throw a RuntimeException with the following message: Insecure use of middleware over HTTP denied by configuration.

By default, localhost is allowed to use HTTP. The security behavior of HttpBasicAuthentication can also be configured to allow:

How to configure a whitelist:

You can list hosts to allow access insecurely. For example, to allow HTTP traffic to your development host dev.example.com, add the hostname to the relaxed config key.

$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "secure" => true,
    "relaxed" => ["localhost", "dev.example.com"],
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ]
]));

Allow HTTPS termination and forwarding

If public traffic terminates SSL on a load balancer or proxy and forwards to the application host insecurely, HttpBasicAuthentication can inspect request headers to ensure that the original client request was initiated securely. To enable, add the string headers to the relaxed config key.

$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "secure" => true,
    "relaxed" => ["localhost", "headers"],
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ]
]));

Allow all unencrypted traffic

To allow insecure usage by any host, you must enable it manually by setting secure to false. This is generally a bad idea. Use only if you know what you are doing.

$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "secure" => false,
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ]
]));

Custom authentication methods

Sometimes passing users in an array is not enough. To authenticate against custom datasource you can pass a callable as authenticator parameter. This can be either a class which implements AuthenticatorInterface or anonymous function. Callable receives an array containing user and password as argument. In both cases authenticator must return either true or false.

If you are creating an Enterprise™ software which randomly lets people log in you could use the following.

use Tuupola\Middleware\HttpBasicAuthentication\AuthenticatorInterface;
use Tuupola\Middleware\HttpBasicAuthentication;

class RandomAuthenticator implements AuthenticatorInterface {
    public function __invoke(array $arguments): bool {
        return (bool)rand(0,1);
    }
}

$app = new Slim\App;

$app->add(new HttpBasicAuthentication([
    "path" => "/admin",
    "realm" => "Protected",
    "authenticator" => new RandomAuthenticator
]));

Same thing can also be accomplished with anonymous function.

$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "realm" => "Protected",
    "authenticator" => function ($arguments) {
        return (bool)rand(0,1);
    }
]));

Setting response body when authentication fails

By default plugin returns an empty response body with 401 response. You can return custom body using by providing an error handler. This is useful for example when you need additional information why authentication failed.

$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/api",
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ],
    "error" => function ($response, $arguments) {
        $data = [];
        $data["status"] = "error";
        $data["message"] = $arguments["message"];

        $body = $response->getBody();
        $body->write(json_encode($data, JSON_UNESCAPED_SLASHES));

        return $response->withBody($body);
    }
]));

Usage with PDO

For those in hurry there is a ready made PDO authenticator. It covers most of the use cases. You probably end up implementing your own though.

use Tuupola\Middleware\HttpBasicAuthentication\PdoAuthenticator;

$pdo = new PDO("sqlite:/tmp/users.sqlite");
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "realm" => "Protected",
    "authenticator" => new PdoAuthenticator([
        "pdo" => $pdo
    ])
]));

For better explanation see Basic Authentication from Database blog post.

Usage with FastCGI

By default Apache does not pass credentials to FastCGI process. If you are using mod_fcgi you can configure authorization headers with:

FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization

Testing

You can run tests either manually or automatically on every code change. Automatic tests require entr to work.

$ make test
$ brew install entr
$ make watch

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

License

The MIT License (MIT). Please see LICENSE for more information.

slim-basic-auth's People

Contributors

3ace avatar acinader avatar ducatel avatar mustikkakeitto avatar piotr-cz avatar tuupola avatar twish avatar urlund avatar vool avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

slim-basic-auth's Issues

Implementation issues while running on IIS8 (Azure WebApp)

Hi There!

I got an internal server error when im using the following components:

  • SlimFramwork 2.6.3
  • HttpBasicAuthentication (latest 2.x)

I'm using the following placement of the files:
index.php
web.config

/Slim:
Environment.php
Log.php
LogWriter.php
Middleware.php
Route.php
Router.php
Slim.php
View.php

/Slim/Exception:
Pass.php
Stop.php

/Slim/Helper:
Set.php

/Slim/Http:
Cookies.php
Headers.php
Request.php
Response.php
Util.php

/Slim/Middleware:
ContentTypes.php
Flash.php
HttpBasicAuthentication.php
MethodOverride.php
PrettyExceptions.php
SessionCookie.php

/Slim/Middleware/HttpBasicAuthentication:
ArrayAuthenticator.php
AuthenticatorInterface.php
PdoAuthenticator.php
RequestMethodRule.php
RequestPathRule.php
RuleInterface.php

And the following lines to add the middleware:

$app = new \Slim\Slim();

$app->add(new \Slim\Middleware\HttpBasicAuthentication([
"path" => "/api",
"realm" => "Protected",
"users" => [
"someone" => "test"
]
]));

Basic case-insensitive and PHP_AUTH_USER

Hi,

I have the following code:

$app->add(new \Slim\Middleware\HttpBasicAuthentication([
	"path" => ["/auth", "/user", "/search"],
	"realm" => "Protected",
	"authenticator" => new PdoAuthenticator([
		"pdo" => $authenticator_pdo,
		"table" => "users",
		"user" => "username",
		"hash" => "password_hash"
	]),
	"callback" => function ($request, $response, $arguments) {
		print_r($arguments);
	},
	"error" => function ($request, $response, $arguments) {
		return $response->withJson(array('error' => 'AUTHENTICATION_FAILED'), 403);
	}
]));

// Check HTTP Basic Authentication
$app->get('/auth', function ($request, $response, $args) {
	$auth_username = $_SERVER['PHP_AUTH_USER'];
	// Return
	return $response->withJson(array(
		'username' => $auth_username,
		'status' => 'OK'
	), 200);
});

If I pass in the header "Authorization: Basic" (upper case B) the authentication is successful and PHP_AUTH_USER is set:

curl 'http://localhost:8080/auth' -H 'Authorization: Basic bmlsczp0ZXN0MTIzNA=='
Array
(
    [user] => nils
    [password] => test1234
)
{"username":"nils","status":"OK"}

If I pass in the header "Authorization: basic" (lowercase letter b) the authentication is successful and PHP_AUTH_USER is not set.

curl 'http://localhost:8080/auth' -H 'Authorization: basic bmlsczp0ZXN0MTIzNA=='
Array
(
    [user] => nils
    [password] => test1234
)
{"username":null,"status":"OK"}

When I remove the case-insensitive (/i) Regular Expression in HttpBasicAuthentication.php then the authentication with basic (lowercase letter b) fails:

curl 'http://localhost:8080/auth' -H 'Authorization: basic bmlsczp0ZXN0MTIzNA=='
{"error":"AUTHENTICATION_FAILED"}

That would be better in my case. I am briefly overflown the RFCs. Basic is always written with (upper case B).

Best regards
Nils

Slim Runtime Exception in iis

Insecure use of middleware over HTTP denied by configuration.
tuupola\slim-basic-auth\src\HttpBasicAuthentication.php
Line: 97

How to configure path and ignore in below case?

Hi,

I just installed this middleware and would like to seek your support on configuring path and ignore in such circumstances.

I am using Slim.

  1. http://api/ will direct to my API doc, no authentication
  2. http://api/hello will prompt some explanation, no authentication
  3. All others, in the form of http://api/a/b or http://api/a/b/c, etc are the API invokation, need authentication. a, b, c above will be different for various API calls.

Thanks!

BasicAuth does not work if password includes :

Try to set the user password to pass:word and the received line will be
user:pass:word
The following explode will not work as expected

From HttpBasicAuthentication.php:

    if (isset($server_params[$this->options["environment"]])) {
        if (preg_match("/Basic\s+(.*)$/i", $server_params[$this->options["environment"]], $matches)) {
            list($user, $password) = explode(":", base64_decode($matches[1]));
        }
    } else {

This should be ok:

            list($user, $password) = explode(":", base64_decode($matches[1]), 2);

Philippe

Passthrough not working properly

Why my passthrough doesn't work?
I want that the route "user/add" of my rest API, do not require authentication,. But unfortunately it doesn't work. Can you please, help me?
Many thanks

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
"path" => ["/"],
"secure" => false,
"passthrough" => "user/add",
"authenticator" => new PdoAuthenticator([
"pdo" => $pdo,
"table" => "users",
"user" => "username",
"hash" => "password"
])
]));

Argument 1 passed to Slim\Slim::add() must be an instance of Slim\Middleware

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim(array(
    'debug' => true
));

$app->add(new \Slim\Middleware\HttpBasicAuthentication([
     "secure" => false,
     "users" => [
         "root" => "root",
     ]
]));

Catchable fatal error: Argument 1 passed to Slim\Slim::add() must be an instance of Slim\Middleware, instance of Slim\Middleware\HttpBasicAuthentication given, called in /home/c19193/public_html/index.php on line 18 and defined in /home/c19193/public_html/lib/Slim/Slim.php on line 1267

What is wrong with my configuration?

Slim 2, Slim\Middleware\HttpBasicAuthentication for Slim 2

ArrayAuthenticator class error

Hi i just found some errors in your code and debugged it

`namespace Slim\Middleware\HttpBasicAuthentication;

class ArrayAuthenticator implements AuthenticatorInterface
{

public $options;

public function __construct($options = null)
{

    /* Default options. */
    $this->options = [
        "users" => []
    ];
		
    if ($options) {
        $this->options = array_merge($this->options, (array)$options);
    }
		
}

public function __invoke(array $arguments)
{
    $user = $arguments["user"];
    $password = $arguments["password"];

    /* Unknown user. */
    if (!isset($this->options["users"]["user"])) {
        return false;
    }

    if (self::isHash($this->options["users"]["password"])) {
        /* Hashed password. */
        return password_verify($password, $this->options["users"]["password"]);
    } else {
        /* Cleartext password. */
        return $this->options["users"]["password"] === $password && $this->options["users"]["user"] === $user;
    }
}

public static function isHash($password)
{
    return preg_match('/^\$(2|2a|2y)\$\d{2}\$.*/', $password) && (strlen($password) >= 60);
}

}`

Setting response body when authentication fails

Hi Mika, thanks for the great middleware :)

In the code example for the above section in the readme, to return a proper JSON response (and not a HTML/text response) you should use:

return $response->withJson($data);

Custom error function still returning error 401 without body

Hi there, I took the code from the example and tried to enter bad credentials. I can't get the custom body to show up in the response: i just get the empty body with a 401 error response. Can there be a reason for such behaviour?

$app = new \Slim\App;

$app->add(new \Slim\Middleware\HttpBasicAuthentication([
    "path" => "/api",
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ],
    "error" => function ($request, $response, $arguments) {
        $data = [];
        $data["status"] = "error";
        $data["message"] = $arguments["message"];
        return $response->write(json_encode($data, JSON_UNESCAPED_SLASHES));
    }
]));

Config to allow 'https forward'

I ran into "Insecure use of middleware over HTTP denied by configuration." when I deployed and found this discussion of the issue in #12

I have worked around the problem by setting "secure" => "false".

However, I think that a better solution would be to allow HttpBasicAuthentication to be configured to permit forwarded https requests.

The use case is where a load balancer or cdn is terminating https requests which are then forwarded over http to slim.

An example implementation can be found here: https://github.com/oscarotero/psr7-middlewares/blob/master/src/Middleware/Https.php#L110

By implementing, testing and documenting this configuration capability, slim-basic-auth would help the end user to securely and quickly set up basic authentication in what I assume is a common deployment scenario.

Advising against hard-coding username/password in the code

While I can understand the want to keep it "basic" I'd advise against allowing (and recommending) people to set up hard-coded username/passwords directly in the code. This leads to them checking them in to version control and makes for a highly insecure system.

I'd suggest making a "loader" system (maybe file, database, etc versions) or something in its place that can parse a list of values from another source. For example, a file loader could access a file outside of the document root with lines in a username:password format.

If you wanted to take it even further, I'd recommend using hashing on the password values. The password API makes this trivial.

godaddy: cannot login

Hello,

after few tests, I was unable to login, the page was asking for user and pass continuosly
I have var_dumped user and pass on the page, but the values were null

url: http://zaporojandesign.ro/admin

user: root
pass: toor (not t00r)

user: user
pass: passw0rd

my question is, how could I investigate what happens ? I'm using godaddy as hoster and have no https. Maybe I have to tweek some php settings or could .htaccess can be the problem ?

Fatal error insecure use of middleware

Copy pasted your example into index.php with users, t00r and I get this error:

Fatal error: Uncaught exception 'RuntimeException' with message 'Insecure use of middleware over HTTP denied by configuration.' in /home/httpd/testapi/vendor/tuupola/slim-basic-auth/src/HttpBasicAuthentication.php:92
Stack trace:
#0 /home/httpd/testapi/vendor/slim/slim/Slim/Slim.php(1302): Slim\Middleware\HttpBasicAuthentication->call()
#1 /home/httpd/testapi/public/index.php(96): Slim\Slim->run()
#2 {main}
  thrown in /home/httpd/testapi/vendor/tuupola/slim-basic-auth/src/HttpBasicAuthentication.php on line 92

Any idea?

php 7 without user and password

When i test a token request without sending user nor password it return a good token.
I i send user with wrong password it returns unauthorized

Does the 'path' parameter support wildcards?

I have a lot of paths that include variables, like /test/:variable1/stats, things like that. Wondering if I can use those style paths directly in the 'path' parameter when initializing the http auth?

Another related question, does path support wildcards? I have a lot of endpoints that hit /v1/something, so I'd like to require auth on all of them... 'path' => "/v1/*" doesn't seem to work.

Keeps asking to login

this code works in my development environment:

$app->add(new \Slim\Middleware\HttpBasicAuthentication(
  [
    "path" => "/admin",
    "secure" => false,
    "users" => [
      "admin" => "admin"
    ]
  ]
));

But on my production server is keeps asking over and over for the password (the error message is that authentication failed.

However, changing the path to "path" => "admin" fixed the issue immediately (and on page reload I didnt have to login again)

Just a heads up for any others running into this

Allow access to $app from within authenticator, error

Useful in many cases to have access to $app and container. E.g. In error, it would be useful to have access to the renderer ($app->getContainer()->get('view') in order to render an error page.

In authenticator, also useful to access app's Model methods, settings, etc.

Can't sign in

Hello,
I can't connect to my app on remote server. It works on local but not on remote server :

$application->add(new HttpBasicAuthentication([
    'realm' => 'Piso',
    'secure' => true,
    'relaxed' => ['localhost'],
    'users' => [
        'root' => '$2y$10$TJor1LmWl5Vi9Ljrqp5Fr.S5TdIUbleIei9.Ndo0gT1IO0/ELwKyK',
        'test' => 'azerty'
    ]
]));

I use "tuupola/slim-basic-auth": "^3.0" .

Thank you

Custom Authentication Method - Passing Error Messages

How would you pass back a custom error message from a custom authenticator? Obviously my example below is pulled completely out of thin air and would never work, but I think you get what I mean? Somehow, there must be a way to pass a message from here, back to the error handler, or alter the $arguments?

class DbAuthenticator implements AuthenticatorInterface {
    private $settings;
 
    public function __construct($settings) {
        $this->settings = $settings;
    }
 
    public function __invoke(array $arguments) {
        if (wrongPassword($user, $pass)) {
            $returnAmessageSomeHow = "Invalid password";
            $failedLogins = $failedLogins + 1;
            return false;
        } 
        if (invalidUsername($user, $pass)) {
            $returnAmessageSomeHow = "Invalid username";
            return false;
        }
    }

}

then...

$container["HttpBasicAuthentication"] = function ($container) {
    return new HttpBasicAuthentication([
        "path" => [ ... ],
        "authenticator" => new DbAuthenticator($container['settings']),
        "error" => function ($request, $response, $arguments) {
            $data = [];
            $data["status"] = "error";
            $data["message"] = $messageReturnedFromAuthenticatorSomehow;
            return $response->write(json_encode($data, JSON_UNESCAPED_SLASHES));
        }
    ]);
};

Always getting "401 Unauthorized" - Apache 2.4.29 and PHP 7.2

Hi,

I'm using v2.3.0 (to maintain compatibility with my remote hosting server where I have PHP 7.0).
I have created a Docker container (webdevops/php-apache:ubuntu-18.04) for a fast PHP / Apache2 system where I can test my REST interface.
There I have:

  • Ubuntu 18.04
  • PHP 7.2.7-0ubuntu0.18.04.2
  • Apache 2.4.29

Here is my code:

$this->slimObj = new \Slim\App();

$this->slimObj->get("/test", function($request, $response, $arguments) {
    print "test";
});

$this->slimObj->add(new \Slim\Middleware\HttpBasicAuthentication([
    "path" => "/",
    "secure" => false,
    "users" => [
        "root" => "password"
    ]
]));

Call:

curl localhost:9080/server/test.php/test --user root:password --include

Response:

HTTP/1.1 401 Unauthorized
Date: Sun, 12 Aug 2018 12:56:47 GMT
Server: Apache/2.4.29 (Ubuntu)
WWW-Authenticate: Basic realm="Protected"
Content-Length: 0
Content-Type: text/html; charset=UTF-8

Made many attempts, no luck!
Any help please?
Also tried with new v3.0, same issue.

Inject authorized users inside a route - Database connection defined by parameter

Hello,

I've an API that needs to set the list of authorized users and passwords in a route because each account has a separate database.

Example:

$app->get('/status/{account}', function ($request, $response, $args) { 
  // connect to account database and check status
  return $response->withJson($data);
});

Is there any way to inject into \Slim\Middleware\HttpBasicAuthentication the list of authorized users and passwords in this context?

Thanks!

Pass email address to error callback

I just broke my API thinking that the arguments passed to the error callback had the email address in them.

Use case: logging failed authentication attempts

Is this something that could be added in the 2.x branch?

Logout feature

Please add an explanation on how is it possible to make a logout feature with this auth method. Or if it's not possible now, maybe it will be a good idea to make it?
Thanks.

Can't get Authorization header using fastCGI

This isn't really an issue, I just can't use this workaround:
FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization

I was trying to use the environment option:
"environment" => "REDIRECT_HTTP_AUTHORIZATION"

but this is not implemented for slim v3. Any special reason?

jQuery Basic Auth

I've tried:

ajax username,password
and
data: {username: "user", password: "password"},
and
xhr.setRequestHeader(
'Authorization',
'Basic ' + btoa('user:password'));
},

What headers need to be passed to work with this middleware?

$callable

Hi!

I've tried to use your Middlerware together with Slim 3.2.2. As IDE I'm using PHP Storm.
I get an error in the function

private function shouldAuthenticate(RequestInterface $request)
{
    /* If any of the rules in stack return false will not authenticate */
    foreach ($this->rules as $callable) {
        if (false === $callable($request)) {
            return false;
        }
    }
    return true;

on "$callable" Function name must be a callable. What could be the problem?

greets

-René

path not working

I have problems to get it to work. When specify a "path", then it doesnt ask for authentication. I believe that the "path" I provide does not match. When I omit the "path"-Option, everything works as expected.
Maybe there is an issue with my .htaccess configuration?
I tried to use it together with slim-jwt-auth. The JwtAuthentication is working as expected.
The root of my Slim-App is under example.com/api. Therefore I use a .htacces to rewrite the URL:

RewriteEngine On
RewriteBase /api

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

My Slim-Code looks like this:

$app = new \Slim\App();
$app->add(new \Slim\Middleware\JwtAuthentication([
    "path" => "/jwttest", // or ["/api", "/admin"]
    "secret" => "supersecretkeyyoushouldnotcommittogithub"
]));

$app->add(new \Slim\Middleware\HttpBasicAuthentication([
    "path" => "/admin", //does not ask for authentication when i visit example.com/api/admin
    "users" => [
        "root" => "t00r",
        "user" => "passw0rd"
    ]
]));

$app->get("/", function() {
    echo "No password needed.";
});

$app->get("/admin", function() {
    echo "API protected by password";
});

//the following is working as expected:
$app->get("/jwttest", function() {
    echo "API protected by JWT";
});

Is there a difference, how the path is retrieved from the Slim-App between JwtAuthentication and HttpBasicAuthentication?

PHP Fatal error: Uncaught Error: Class 'Slim\\Middleware\\HttpBasicAuthentication' not found

Im having a strange error.

On my localhost (windows10 with xampp) all my slim api is working fine, but when i put it on my server (ubuntu) i've got the error:
PHP Fatal error: Uncaught Error: Class 'Slim\Middleware\HttpBasicAuthentication' not found /var/www/html ...

Some useful notes:
My composer.php
{
"require": {
"slim/slim": "^3.9",
"tuupola/slim-basic-auth": "^3.0",
"slim/middleware": "*",
"firebase/php-jwt": "^5.0",
"tuupola/slim-jwt-auth": "^3.0",
"tuupola/base62": "^0.10.0",
"tuupola/cors-middleware": "^0.7.0"
}
}

My bootstrap.php
$app->add(new \Tuupola\Middleware\HttpBasicAuthentication([

"users" => [
    "root" => "toor"
],
"path" => ["/"],
/**
 * Whitelist - Protege todas as rotas e só libera as de dentro do array
 */
"passthrough" => ["/auth"]

]));

Can you please give some tips?
Thank you

There is a way to update request in callback ?

Hi,

There is a way to add an attribute/header in the request in callback (or authenticator) method ?

Currently I did that in two steps:

  1. In authenticator when credentials are correct I set my attribute in session
  2. In a second middleware I check if the attribute exist in session and I set it to the request

So I would be nice if it's possible to update the request in this middleware.

Thanks for your help ;)

Change the documentation

Change the

\Slim\Middleware\HttpBasicAuthentication

to

\Tuupola\Middleware\HttpBasicAuthentication

since it's displaying that the class is missing.

Slim Application Error: Basic auth not working properly

Why can't I authenticate with postman Basic Auth (username: root, password: t00r). The /open/test route works just fine

<?php
require '../../vendor/autoload.php';
$app = new \Slim\App();
$app->add(new \Slim\Middleware\HttpBasicAuthentication(array(
    "path" => "/close",
    "realm" => "Protected",
    "users" => array(
        "root" => "t00r",
        "user" => "passw0rd"
    )
)));
$app->get('/open/test', 'getOpen');
$app->get('/close/test', 'getClose');
function getOpen() {
    echo "Success Open";
}
function getClose() {
    echo "Success Close";
}
$app->run();

Installing for Slim 3.0@RC, version error

Attempting to install result in that error.

Problem 1
Installation request for tuupola/slim-basic-auth ^1.0 -> satisfiable by tuupola/slim-basic-auth[1.0.0]

tuupola/slim-basic-auth 1.0.0 requires slim/slim ~2.3 -> no matching package found

My actual composer.json
"require": {
"slim/slim": "^3.0@RC",
"tuupola/slim-jwt-auth": "^2.0",
"slim/csrf": "^0.5.0",
"ircmaxell/password-compat": "^1.0"
}

Always returns Authentication failed

Hi, I used the middleware for a time and it's works ok, an in a time to here always return error in the authentication when I try to insert another user. I return to the old status but don't work.

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([ "secure" => false, "users" => [ "test" => "secret", "test-2" => "secret2" ], "error" => function ($response, $arguments) { $data["status"] = "error"; $data["message"] = $arguments["message"]; return $response ->withHeader("Content-Type", "application/json") ->getBody()->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)); } ]));

I'm using version 3 and have php 7.1. What can do the problem?

Enhancement: require auth only for specified HTTP method

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.

Branch 2.x

How do I install the 2.x branch for use with PHP 7.0 in my project?

Using outside index.php

Hi, I'm a bit new with frameworks but trying to understand how to fix the puzzle.

I got basic auth working by adding the code in index.php of slim after the $app has been instantiated. But I don't really want it there and instead want it in my API controller where I have all my other code.

So I put the same code in the controller __construct, but that did not seem to work as it does not require authentication on a request.

I moved it to another function called secure() in the controller and called it by $this->secure();

Did not work either. It doesn't throw any errors, it just doesn't require auth.

So what is the recommended way to use this somewhere else in the framework? Such as a API controller for example? Or can it be called and included on routing level?

Any guidelines and examples are welcomed.

Thanks!

unauthorized response, with php 7.1

Always getting an unauthorized response, with php 7.1.18, on the shared hostgator server, everything works perfectly locally (php7.2 OR 7.1.18). Can someone help me ?

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/v1",
    "secure" => false,
    "relaxed" => ["localhost"],
    "users" => [
        "teste" => 'teste',
    ]
]));

'Insecure use of middleware' error when accessing a route outside of 'path' setting

Configure app like so:

$app = new \Slim\Slim();

$app->add(new \Slim\Middleware\HttpBasicAuthentication([
  'path' => '/admin',
  'relaxed' => [],
  'users' => ['admin' => 'password'],
]));

$app->get('/', function () use ($app) {
  $app->response->setBody('Hello!');
});

$app->run();

Now browse to http://localhost:3000. One would expect Hello! to be outputted but instead we receive an Insecure use of middleware error.

It seems that the plugin is checking all requests for HTTPS, not just requests to /admin.

Composer "Invalid version string"

Error when updating with composer update --no-dev:

  [RuntimeException]                                                           
  Could not load package tuupola/slim-basic-auth in http://packagist.org: [Un  
  expectedValueException] Could not parse version constraint ^2.3: Invalid ve  
  rsion string "^2.3"  

PHP Fatal error: Uncaught TypeError: Return value of Tuupola\\Middleware\\HttpBasicAuthentication::authenticator()

Hello friends!
Am I facing an unprecedented error, can you help me?

PHP Fatal error: Uncaught TypeError: Return value of Tuupola\\Middleware\\HttpBasicAuthentication::authenticator() must be an instance of Tuupola\\Middleware\\void, none returned in /var/www/dashboard.mobi/plataforma/api/vendor/tuupola/slim-basic-auth/src/HttpBasicAuthentication.php:228\nStack trace:\n#0 [internal function]: Tuupola\\Middleware\\HttpBasicAuthentication->authenticator(Object(Tuupola\\Middleware\\HttpBasicAuthentication\\PdoAuthenticator))\n#1 /var/www/dashboard.mobi/plataforma/api/vendor/tuupola/slim-basic-auth/src/HttpBasicAuthentication.php(171): call_user_func(Array, Object(Tuupola\\Middleware\\HttpBasicAuthentication\\PdoAuthenticator))\n#2 /var/www/dashboard.mobi/plataforma/api/vendor/tuupola/slim-basic-auth/src/HttpBasicAuthentication.php(55): uupola\\Middleware\\HttpBasicAuthentication->hydrate(Array)\n#3 /var/www/dashboard.mobi/plataforma/api/src/middleware.php(19): Tuupola\\Middleware\\HttpBasicAuthentication->__construct(Array)\n#4 /var/www/dashboard.mobi/plataforma/api/public/index.php(30): require('/var/www/dashbo...') in /var/www/dashboard.mobi/plataforma/api/vendor/tuupola/slim-basic-auth/src/HttpBasicAuthentication.php on line 228

Authentication using login form

Hello.

How to pass my form login variables to pdo authentication.

using like rest api is all ok, but i can log in using form.

thanks

Get Current User

Hi,

How to get the current user who is requested?

$app->get('/bank/list',function () {
$currentUser = ????? <---- any some method for get current user?
$sql = "SELECT * FROM bank WHERE userId = ." currentUser;
$stmt = getDB()->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
echo json_encode($result);
}
);

sorry for bad english

Thx

Multiple Paths

I want to setup authentication on multiple paths for my API. In most cases I'll need authentication but in others I definitely don't want authentication (i.e. registration). I know I can create separate instances of \Slim\Middleware\HttpBasicAuthentication but is there a way to create a single instance that includes multiple paths?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.