cakephp 具有错误凭据的API重定向到html登录表单

shyt4zoc  于 2022-11-11  发布在  PHP
关注(0)|答案(1)|浏览(157)

我用CakePHP 4创建了一个新的应用程序。为了验证我使用了CakeDC/users插件。它工作得很好。我可以登录到应用程序。
我还按照以下说明添加了REST API:REST - 4.x
对于API的身份验证,我使用基于令牌的身份验证,它运行良好。对于API,我创建了一个新前缀:

$routes->prefix('Api', function (RouteBuilder $routes) {
    $routes->setExtensions(['json']);
    $routes->fallbacks(DashedRoute::class);
});

这是在users.php中的配置:

'Auth.Authenticators.Token' => [
        'className' => 'Authentication.Token',
        'skipTwoFactorVerify' => true,
        'header' => 'authorization',
        'queryParam' => 'api_token',
        'tokenPrefix' => 'Token',        
        'unauthenticatedRedirect' => null
    ],

当我输入错误的令牌时发生问题。API返回HTML登录表单。我希望返回401。

有没有什么好的教程或者什么提示,怎么样才能解决这个问题?
转肽酶

kcwpcxri

kcwpcxri1#

我创建了自定义的unauthorizedHandler类,它工作正常。
在config/users.php中我添加了这一行:

'Auth.AuthorizationMiddleware.unauthorizedHandler.className' => 'CustomRedirect',

并在src/Middleware/UnauthorizedHandler目录中创建了一个新的文件CustomRedirectHandler.php。
也是我当时遗漏了的接受:应用程序/json标头。

相关问题