wob*_*ano 4 php basic-authentication slim
今天是个好日子!
我在这里有一个带有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');
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用弹出登录框登录时,它可以工作,但我真的想将它重定向到我的登录页面而不是那个页面。
任何帮助将非常感激。
中间件实现HTTP 基本访问身份验证。身份验证对话框通过响应标头触发。由浏览器供应商决定如何询问凭据。大多数浏览器使用您描述的弹出登录对话框。
您尝试做的是使用 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");
}
]));
Run Code Online (Sandbox Code Playgroud)
但是,使用上面的代码,您仍然必须以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...");
}
});
Run Code Online (Sandbox Code Playgroud)