我已经创建了一些apis,它们工作得很好。现在,当有人点击web浏览器上get请求受保护apis时,它将重定向到身份验证系统的登录。如何覆盖此功能?
完整详细信息
我的工作是在laravel应用程序中,我已经实现了护照和身份验证系统。这个项目到目前为止还没有任何web界面。这是我的api.php
Route::group(['middleware' => ['auth:api'],'namespace' => 'Api', 'prefix' => '/v1'], function () {
Route::get('/user/profile', 'UserController@profile');
Route::get('/logout', 'Auth\LoginController@logout');
});
Route::group(['middleware' => ['api'], 'namespace' => 'Api', 'prefix' => '/v1'], function () {
Route::post('/auth/register', 'Auth\RegisterController@create');
Route::post('/auth/login', 'Auth\LoginController@login');
Route::post('/auth/password/email', 'Auth\ForgotPasswordController@getResetToken');
Route::post('/auth/password/reset', 'Auth\ResetPasswordController@reset');
});
这是我的web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
当我击球时
{{site_url}}/api/v1/user/profile
如果在postman中没有传递或带有无效的访问令牌,则它将返回以下错误(this is OK)。
{"status":"fail","success":0,"error":401,"message":"Invalid Token!"}
但是当我在网络浏览器中点击这个url时,它会将我重定向到登录页面。
发布于 2018-05-27 15:07:12
我通过向/app/Exceptions/Handler.php
添加以下函数解决了这个问题:
public function unauthenticated($request, AuthenticationException $exception){
if($request->expectsJson()){
return response()->json('Please login',401);
}
return redirect()->guest('admin/login');
}
public function unauthorized($request, AuthorizationException $exception){
if($request->expectsJson()){
return response()->json("You don't have permission to do this",401);
}
return redirect()->guest('login');
}
https://stackoverflow.com/questions/50549537
复制相似问题