Laravel Airlock 如何 return 对未经身份验证的 Web 和 api 请求的不同响应
Laravel Airlock how to return different responses for unauthenticated web and api requests
我正在使用 laravel + React Native 开发移动应用程序和网站。
当您向带有 "auth:airlock" 中间件的路由发送请求时,如果您传递了错误的 Bearer 令牌,它会将您重定向到 /login 页面。我想 return 响应("Unauthenticated",403)。但是,与此同时,我想继续将未经身份验证的用户重定向到我的网络用户的 /login 页面。
所以我想实现:
当未经身份验证的网络用户尝试浏览:域。com/settings,他将重定向到域。com/login页面。
当请求到达域时。com/api/settings,如果请求没有Bearer token或错误的Bearer token,响应将是json。
解决方案是:
api.php中的新路线:
Route::get("/unauthenticated", function(Request $request) {
return response("Unauthenticated", 403);
})->name("unauthenticated");
在Authenticate.php中间件中编辑:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
if($request->is("api/*")) {
return route("unauthenticated");
}
return route('login');
}
}
我想说最干净的解决方案是将来自 React Native 的请求发送为 ("application/json")。
在这种情况下,Laravel 将确定它是一个 API 调用,并且不会重定向到 route("login")
以下是 App\Http\Middleware\Authenticate
的摘录:
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
我正在使用 laravel + React Native 开发移动应用程序和网站。
当您向带有 "auth:airlock" 中间件的路由发送请求时,如果您传递了错误的 Bearer 令牌,它会将您重定向到 /login 页面。我想 return 响应("Unauthenticated",403)。但是,与此同时,我想继续将未经身份验证的用户重定向到我的网络用户的 /login 页面。
所以我想实现:
当未经身份验证的网络用户尝试浏览:域。com/settings,他将重定向到域。com/login页面。
当请求到达域时。com/api/settings,如果请求没有Bearer token或错误的Bearer token,响应将是json。
解决方案是:
api.php中的新路线:
Route::get("/unauthenticated", function(Request $request) {
return response("Unauthenticated", 403);
})->name("unauthenticated");
在Authenticate.php中间件中编辑:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
if($request->is("api/*")) {
return route("unauthenticated");
}
return route('login');
}
}
我想说最干净的解决方案是将来自 React Native 的请求发送为 ("application/json")。
在这种情况下,Laravel 将确定它是一个 API 调用,并且不会重定向到 route("login")
以下是 App\Http\Middleware\Authenticate
的摘录:
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}