如何返回当前已验证用户的JSON表示?我看到Laravelroutes/api.php
有一个方法:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
但当我试图到达路线时,我遇到了一个错误,
InvalidArgumentException
Route [login] not defined.
我也尝试过创建自己的路线,但没有成功。我怎样才能做到这一点?
我的解决方案:
要解决此问题,只需执行以下更改:
AppExceptionsHandler.php
namespace AppExceptions;
use Exception;
use IlluminateFoundationExceptionsHandler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @param Exception $exception
* @return IlluminateHttpResponse
*/
public function render($request, Exception $exception)
{
return response()->json(
[
'errors' => [
'status' => 401,
'message' => 'Unauthenticated',
]
], 401
);
}
}
只需传递标题:
Accept: application/json
缺少路由登录
由于您未使用有效的API令牌进行身份验证,auth:API-midleware重定向到名为"login"的路由。
要架设这条路线,你可以进行
php artisan make:auth
或者自己动手web.php
Route::get('login', function () {
//
})->name('login');
并将用户json检索代码更改为
当前用户为json
在web.php中输入:
Route::middleware('auth.basic')->get('/user', function (Request $request) {
return Auth::user();
});
如果你仍然想把它放在api.php中,你需要应用"web"中间件。
为仍然需要的人。
-
添加到标头请求
Accept: application/json
-
强制或想要自定义JSON响应
在app/Exceptions/Handler.php
编辑渲染函数中
不要忘记在顶部文件中使用:use IlluminateAuthAuthenticationException;
。
public function render($request, Exception $exception)
{
if ($exception instanceof AuthenticationException) { //check if exception is error of Auth
if($request->expectsJson()){ //check if request accept json, remove it if you don't want
return response([ //here is your custom response
"status" => 0,
"msg" => "INVALID_TOKEN"
]);
}
}
return parent::render($request, $exception);
}