有没有办法改变 auth:api 的响应,A laravel api_token
Is there any way to change response of auth:api , A laravel api_token
我正在用 Default api-authentication
创建 API
我正在使用 laravel 6.x
它 运行 当我在用户注册上生成并通过请求传递生成的令牌时。
但是
- 当我传递错误的令牌时,它会显示登录页面 HTML,我想显示一些自定义 JSON 响应而不是 HTML
- 还有什么方法可以检查传递的令牌是否与传递的用户 ID 相同。因为用户可以使用令牌传递不同的用户 ID。
我的api
路由文件如下
Route::middleware('auth:api')->post('/listUser', 'ApiController@listUser');
您可以在 Authenticate
中间件中配置自定义响应。例如
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($guard === 'api') {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
您可以通过使用您的自定义逻辑扩展 TokenGuard
来做到这一点。或者您可以创建一个新的中间件,它断言通过 API 验证的用户与传递的用户 ID 匹配。
我的积分管理如下
第 1 点
- 当我传递错误的令牌时,它会显示登录页面 HTML,我想显示一些自定义 JSON 响应而不是 HTML
我在 App/Exceptions/handler.php
中进行了更改
修改render function
如下
public function render($request, Exception $exception)
{
if ($exception instanceof NotFoundHttpException) {
if ($request->is('api/*')) {
return response()->json(['error' => 'Not Found'], 404);
}
//return response()->view('404', [], 404);
}
return parent::render($request, $exception);
}
它工作得很好,因为我有一个基于 api
的路由
我的api路线看起来像
// Request with Authentication v1
Route::group(['prefix' => 'v1', 'namespace' => 'Api\v1', 'middleware' => ['api','auth:api'] ], function () {
Route::post('/myProfile', 'ApiController@myProfile');
});
// Request without Authentication v1
Route::group(['prefix' => 'v1', 'namespace' => 'Api\v1', 'middleware' => 'api'], function () {
Route::post('/register', 'ApiController@register');
});
对于点 2
- 还有什么方法可以检查传递的令牌是否与传递的用户 ID 相同。因为用户可以通过令牌传递不同的用户 ID。
为此,我在 ApiController
中创建了一个函数 checkValidations
并检查 user id
是否与特定的 token
关联,如下所示:
在那个函数中我检查的方式是
- 检查从调用的方法
传递的所有 validation
- 匹配
token
与 user id
关联,然后 return success
- else
return
无效的令牌响应
函数代码
public function checkValidations($required = [], $request = [])
{
$validator = Validator::make($request->all(), $required);
if ($validator->fails()) {
$this->response[] = array(
'status' => 'false',
'response_msg' => implode(",",$validator->messages()->all()),
);
return array('response' => $this->response);
} else if(isset($request['api_token']) && auth('api')->user()->id ==
$request['id']) {
return 'success';
} else {
$this->response[] = array(
'status' => 'false',
'response_msg' => 'Invalid token',
);
return array('response' => $this->response);
}
}
并从任何函数调用 checkValidations
并可以将其重用为
public function myProfile(Request $request)
{
$validation = [
'id' => 'bail|required|exists:users',
'api_token' => 'bail|required|min:60|max:60'
];
if( $this->checkValidations($validation, $request) == 'success'){
$this->response[] = array(
'status' => 'true',
'response_msg' => 'Success',
'data' => auth('api')->user()
);
}
return array('response' => $this->response);
}
可能还有很多其他最好的方法来管理这些点,但我没有找到,所以我用上面的方法来管理。
我刚刚验证了与身份验证相关的异常类型,然后 URL(因为 API 守卫使用 '/api' 只是验证它)并触发响应.
if($exception instanceof \Illuminate\Auth\AuthenticationException){
if($request->is('api/*')){
return response()->json([
'success' => false,
'message' => 'User not logged'
]);
}
}
我在 app/Exceptions/Handler.php
中进行了以下更改。
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Not Authorized'], 404);
}
return redirect()->guest(route('login'));
}
在文档中添加use Illuminate\Auth\AuthenticationException
。另外,不要忘记将 X-Requested-With:XMLHttpRequest
添加到您的请求 header 中。 (或邮递员中的Headers)
return redirect()->guest(route('login'));
是在您不使用 API 时将您重定向到登录页面。
我正在用 Default api-authentication
创建 API我正在使用 laravel 6.x
它 运行 当我在用户注册上生成并通过请求传递生成的令牌时。
但是
- 当我传递错误的令牌时,它会显示登录页面 HTML,我想显示一些自定义 JSON 响应而不是 HTML
- 还有什么方法可以检查传递的令牌是否与传递的用户 ID 相同。因为用户可以使用令牌传递不同的用户 ID。
我的api
路由文件如下
Route::middleware('auth:api')->post('/listUser', 'ApiController@listUser');
您可以在
Authenticate
中间件中配置自定义响应。例如public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->guest()) { if ($guard === 'api') { return response('Unauthorized.', 401); } else { return redirect()->guest('login'); } } return $next($request); }
您可以通过使用您的自定义逻辑扩展
TokenGuard
来做到这一点。或者您可以创建一个新的中间件,它断言通过 API 验证的用户与传递的用户 ID 匹配。
我的积分管理如下
第 1 点
- 当我传递错误的令牌时,它会显示登录页面 HTML,我想显示一些自定义 JSON 响应而不是 HTML
我在 App/Exceptions/handler.php
修改render function
如下
public function render($request, Exception $exception)
{
if ($exception instanceof NotFoundHttpException) {
if ($request->is('api/*')) {
return response()->json(['error' => 'Not Found'], 404);
}
//return response()->view('404', [], 404);
}
return parent::render($request, $exception);
}
它工作得很好,因为我有一个基于 api
的路由
我的api路线看起来像
// Request with Authentication v1
Route::group(['prefix' => 'v1', 'namespace' => 'Api\v1', 'middleware' => ['api','auth:api'] ], function () {
Route::post('/myProfile', 'ApiController@myProfile');
});
// Request without Authentication v1
Route::group(['prefix' => 'v1', 'namespace' => 'Api\v1', 'middleware' => 'api'], function () {
Route::post('/register', 'ApiController@register');
});
对于点 2
- 还有什么方法可以检查传递的令牌是否与传递的用户 ID 相同。因为用户可以通过令牌传递不同的用户 ID。
为此,我在 ApiController
中创建了一个函数 checkValidations
并检查 user id
是否与特定的 token
关联,如下所示:
在那个函数中我检查的方式是
- 检查从调用的方法 传递的所有
- 匹配
token
与user id
关联,然后 returnsuccess
- else
return
无效的令牌响应
validation
函数代码
public function checkValidations($required = [], $request = [])
{
$validator = Validator::make($request->all(), $required);
if ($validator->fails()) {
$this->response[] = array(
'status' => 'false',
'response_msg' => implode(",",$validator->messages()->all()),
);
return array('response' => $this->response);
} else if(isset($request['api_token']) && auth('api')->user()->id ==
$request['id']) {
return 'success';
} else {
$this->response[] = array(
'status' => 'false',
'response_msg' => 'Invalid token',
);
return array('response' => $this->response);
}
}
并从任何函数调用 checkValidations
并可以将其重用为
public function myProfile(Request $request)
{
$validation = [
'id' => 'bail|required|exists:users',
'api_token' => 'bail|required|min:60|max:60'
];
if( $this->checkValidations($validation, $request) == 'success'){
$this->response[] = array(
'status' => 'true',
'response_msg' => 'Success',
'data' => auth('api')->user()
);
}
return array('response' => $this->response);
}
可能还有很多其他最好的方法来管理这些点,但我没有找到,所以我用上面的方法来管理。
我刚刚验证了与身份验证相关的异常类型,然后 URL(因为 API 守卫使用 '/api' 只是验证它)并触发响应.
if($exception instanceof \Illuminate\Auth\AuthenticationException){
if($request->is('api/*')){
return response()->json([
'success' => false,
'message' => 'User not logged'
]);
}
}
我在 app/Exceptions/Handler.php
中进行了以下更改。
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Not Authorized'], 404);
}
return redirect()->guest(route('login'));
}
在文档中添加use Illuminate\Auth\AuthenticationException
。另外,不要忘记将 X-Requested-With:XMLHttpRequest
添加到您的请求 header 中。 (或邮递员中的Headers)
return redirect()->guest(route('login'));
是在您不使用 API 时将您重定向到登录页面。