【问题标题】:Slim Basic AuthenticationSlim 基本身份验证
【发布时间】:2016-03-26 01:53:53
【问题描述】:

大家好!

我在这里有一个带有slim-basic-auth 的工作苗条代码,当我进入受限目录时,它会显示:

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

我的瘦代码:

$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');
    }

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

任何帮助将不胜感激。

【问题讨论】:

  • 你是如何限制目录的?我猜它是在 PHP 代码运行之前通过 Web 服务器配置发生的。

标签: php slim basic-authentication


【解决方案1】:

中间件实现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...");
   }
});

【讨论】:

    【解决方案2】:

    此时,您似乎不是在尝试使用 Http Basic Authenticator,而是在正常登录过程,因此您需要使用会话等。

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

    $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 标头,使您的登录表单无用,因为它会触发身份验证弹出窗口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2021-06-20
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多