超薄基本身份验证

时间:2016-03-23 01:39:55

标签: php basic-authentication slim http-basic-authentication

大家好日子!

我在slim-basic-auth处有一个有效的瘦身代码,当我转到受限目录时,会显示:

enter image description here

一切正常,但我想做的是将其重定向到我的登录页面而不是显示弹出登录框。这是我的登录页面:

enter image description here

我的瘦身代码:

$pdo = new \PDO("mysql:host=localhost;dbname=databasename", "username");
$app->add(new \Slim\Middleware\HttpBasicAuthentication([
    "path" => "/main",
    "realm" => "Protected",
    "authenticator" => new PdoAuthenticator([
        "pdo" => $pdo,
        "table" => "accounts",
        "user" => "accountUsername",
        "hash" => "accountPassword"
    ]),
    "callback" => function ($request, $response, $arguments) use ($app) {
        return $response->withRedirect('/main/contacts');
    }

当我尝试使用弹出登录框登录时,它可以正常工作但我真的想将其重定向到我的登录页面而不是那个。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

此时,您似乎并未尝试使用Http Basic身份验证器,而是使用正常的登录流程,因此您需要使用会话等。

一个非常简单的例子是将它添加到中间件堆栈的底部。(意味着它将首先被执行,因为它将位于堆栈的顶部)

$middleware = function (Request $request, Response $response, $next) {

    if (!isset($_SESSION['__user'])) {
        //don't interfere with unmatched routes
        $route = $request->getAttribute('route');
        if ($route && !in_array($route->getName(), ['login'])) {
            return $response->withStatus(403)->withHeader('Location', $this->router->pathFor('login'));
        }
    }

    return $next($request, $response);
};
$app->add($middleware);

查看HttpBasicAuthentication中间件,它将始终发送WWW-Authenticate标题,使您的登录表单无用,因为它会触发身份验证弹出窗口。

答案 1 :(得分:2)

中间件实现HTTP Basic Access Authentication。验证对话框通过响应头触发。由浏览器供应商决定如何询问凭据。大多数浏览器都使用您描述的弹出登录对话框。

您尝试做的是使用HTTP基本身份验证的一种非正统方式。但是,您可以通过从响应中删除WWW-Authenticate标头来禁止登录对话框。请注意,至少需要版本2.0.2才能实现此目的。

$app->add(new \Slim\Middleware\HttpBasicAuthentication([
    "path" => ["/main"],
    "authenticator" => new PdoAuthenticator([
        "pdo" => $pdo,
        "table" => "accounts",
        "user" => "accountUsername",
        "hash" => "accountPassword"
    ]),
    "error" => function ($request, $response, $arguments) {
        return $response
            ->withRedirect("/auth/login")
            ->withoutHeader("WWW-Authenticate");
    }
]));

但是,使用上面的代码,您仍然需要以某种方式设置Authentication: Basic请求标头。一种方法是使用AJAX请求。

$.ajax({
   url: "http://example.com/auth/login",
   username: $("username").val(),
   password: $("password").val(),
   success: function(result) {
     alert("Authorization header should now be set...");
   }
});