Authentication 结合使用CakePHP表单和基本身份验证

Authentication 结合使用CakePHP表单和基本身份验证,authentication,cakephp,cakephp-3.x,Authentication,Cakephp,Cakephp 3.x,我使用CakePHP3.8和Authentication 1.0创建了一个简单的测试站点来进行测试。我想使用表单和基本身份验证,因为预期的应用程序将提供REST呼叫 如果未包含HttpBasic,则站点可以正常工作,即显示登录窗口。但是,使用HttpBasic,站点直接进行基本身份验证 代码直接来自烹饪手册 我错过了什么 public function getAuthenticationService(ServerRequestInterface $request, ResponseIn

我使用CakePHP3.8和Authentication 1.0创建了一个简单的测试站点来进行测试。我想使用表单和基本身份验证,因为预期的应用程序将提供REST呼叫

如果未包含HttpBasic,则站点可以正常工作,即显示登录窗口。但是,使用HttpBasic,站点直接进行基本身份验证

代码直接来自烹饪手册

我错过了什么

    public function getAuthenticationService(ServerRequestInterface $request, ResponseInterface $response)
{
    $service = new AuthenticationService();

    $service->setConfig([
            'unauthenticatedRedirect' => '/users/login',
            'queryParam' => 'redirect'
    ]);

    $fields = [
        'username' => 'user',
        'password' => 'password',
    ];

    // Load Identifiers
    $service->loadIdentifier('Authentication.Password', compact('fields'));

    // Load the authenticators
    $service->loadAuthenticator('Authentication.Session');
    $service->loadAuthenticator('Authentication.Form', [
            'fields' => $fields,
            'loginUrl' => '/users/login',
    ]);
    $service->loadAuthenticator('Authentication.HttpBasic');

    return $service;
}

如注释中所述,同时使用form authenticator和HTTP basic authenticator不会工作得太好,这是因为身份验证服务不会停止执行所有加载的身份验证程序,除非其中一个返回指示身份验证成功的响应

这意味着您将始终看到身份验证质询响应,而不会看到您的登录表单。只有实际的身份验证部分才能在该星座中工作,即直接将登录凭据作为表单数据发送到登录端点

如果您实际上不需要阻止您访问登录表单的基本身份验证质询响应,那么您可以使用不会导致质询响应返回的自定义/扩展身份验证程序,它应该像覆盖
\Authentication\authenticator\HttpBasicAuthenticator::unauthorizedChallenge()一样简单

src/Authenticator/ChallengelessHttpBasicAuthenticator.php

namespace-App\Authenticator;
使用Authentication\Authenticator\HttpBasicAuthenticator;
使用Psr\Http\Message\ServerRequestInterface;
类ChallengelessHttpBasicAuthenticator扩展HttpBasicAuthenticator
{
公共功能未经授权的挑战(ServerRequestInterface$request)
{
//努普
}
}
另外,如果应用程序使用身份验证组件的
setIdentity()
方法,即使使用无状态身份验证程序,也可能不需要添加额外的检查,这将导致身份在会话中持久化。如果不希望这样,则需要在设置标识之前测试成功的身份验证程序是否无状态:

$provider=$this->Authentication->getAuthenticationService()->getAuthenticationProvider();
if(!($provider instanceof\Authentication\Authenticator\interface))
{
$this->Authentication->setIdentity(/*…*/);
}

本书中的示例可能不是最好的,同时使用表单验证器和基本验证器不会太好。您的身份验证计划到底是什么样的?您是否真的需要用户代理能够通过表单和HTTP身份验证对相同的端点进行身份验证,或者您是否有单独的API端点?@ndm目标是使用~/Members/add等请求来调用表单身份验证,但对~/Members.json的请求将使用基本身份验证。我设置了与RESTful路由下的示例非常相似的路由。这适用于先前的Auth组件下的应用程序。我明白了,这可能有点棘手。你真的需要浏览器提供的基本身份验证挑战(即用户名/密码的输入提示),还是希望客户端直接向应用程序的端点发送身份验证凭据?@ndm我根本不需要浏览器来使用基本身份验证。最后,我想要一个电子表格,从网站上下拉统计数据,以显示仪表板。此电子表格将提供用户名/密码作为其调用的一部分。
$service->loadAuthenticator(\App\Authenticator\ChallengelessHttpBasicAuthenticator::class);