gpt4 book ai didi

php - Laravel Passport 路由重定向到登录页面

转载 作者:IT王子 更新时间:2023-10-29 00:07:54 26 4
gpt4 key购买 nike

我正在使用 Laravel 5.3 和 Passport。

当使用 Postman 测试我在 api.php 文件中设置的任何路由时,它总是返回登录页面。这是我的测试路线的示例:

Route::get('/getKey', function() {
return 'hello';
})->middleware('client_credentials');

postman 参数:

Accept application/json
Authorization Bearer <then my key>

根据我在搜索答案时发现的另一个解决方案,我已将中间件设置为“auth:api”。

protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('auth:api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}

我已经尝试了几乎所有对其他人有用的解决方案,但仍然没有成功。任何建议将不胜感激。

更新所以我终于得到了一些工作。我创建了一个消费者应用程序并创建了一些测试功能。通过 token 验证,我能够使用 api。但是,点击这条路线不再返回我的登录页面,而是什么都不返回。所以无论出于何种原因,它仍然无法正常工作。

Route::get('/user', function (Request $request) {

return $request->user();
})->middleware('client_credentials');

最佳答案

重定向到已定义的登录路由发生在 app\Exceptions\Handler.php 类中。

protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}

return redirect()->guest(route('login'));
}

该函数会尝试检测它是否被 API 调用(在这种情况下它会返回带有 JSON 消息的 401 未授权响应),如果不是,它将根据注释重定向到登录页面

Converts an authentication exception into an unauthenticated response

要解决 postman 中的问题,请在请求中单击 Headers 选项卡并添加:

key:   Accept
value: application/json

我对此很陌生,所以不确定这是我们在使用 Postman 测试所有 API 调用时应该添加的 header ,还是只是对如何设置此 laravel 方法感到厌烦。

无论如何,这将解决您被重定向到登录页面的问题,但是这表明您的基础身份验证无法正常工作

关于php - Laravel Passport 路由重定向到登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42116452/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com