Laravel-如何在未经授权的情况下取消重定向到登录



在我的项目中,我使用laravel作为api

UserController>配置文件((need token to run

例如,当我在没有令牌的情况下调用它时,laravel显示错误,";未定义路由[登录]">,这是正确的,因为我们在laravel中没有任何模板

如何返回json响应,而将其重定向到登录页面作为html?

public function profile(): JsonResponse
{
//using protected method
return response()->json($this->guard()->user());
}

因此,基本上您可以创建一个自定义的Auth中间件,该中间件返回JSON响应。或者你可以在函数中使用一个简单的条件:

if (Auth::check()){
//if logged in user exists
} else {
//if logged in user does not exist
}

您可以手动制作中间件,并在中间件中检查用户是否存在。例如,如果您使用JWT令牌,那么您可以像这样编写app/Http/Middleware/Authenticate.php:

public function handle($request, Closure $next, $guard = null)
{
/* Check is token filled */
if (!Auth::check()) {
return response()->json([
'success' => false,
'status' => 401,
'message' => 'Bad authorization',
'data' => []
], 401);
}
return $next($request);
}

对于路线分区:

Route::group([
'middleware' => 'auth'
], function () {
Route::get('/profile', 'User@profile');
});

打开身份验证文件app/Http/Middleware/Authenticate.php

添加参考

use Closure;
use IlluminateSupportFacadesAuth;

输入这个代码:

public function handle($request, Closure $next, ...$guards)
{
if (!Auth::guard('api')->check()) {
return response()->json(['message' => 'Error Message!']);
}
return $next($request);
}

要编辑的代码位于函数redirectTo中的app/Http/Middleware/Authenticate.php中

相关内容

最新更新