自定义Laravel Passport响应未经身份验证

时间:2019-05-21 05:30:42

标签: php laravel-passport

目前,我使用Laravel中使用护照功能制作的api具有登录,注册,更新和删除功能。一切正常,可以使用此api很好地插入数据并从数据库中获取数据。现在我想知道,当令牌过期时,如何自定义api的响应。令牌的到期也可以正常工作。它会自动显示此消息

{ "message": "Unauthenticated" }

这是路由的代码,其中受我的Oauth令牌保护,如果该用户未先登录,则该用户未通过身份验证来浏览路由

 Route::middleware('auth:api')->get('/user', function (Request $request){return $request->user();});



Route::post('/timekeeping','Auth\Api\AuthController@timekeeping');

Route::post('/login','Auth\Api\AuthController@login');

 Route::middleware('auth:api')->group(function () {Route::post('/timekeeping_app','Auth\Api\AuthController@timekeeping_app');

Route::post('/logout','Auth\Api\AuthController@logout');

Route::post('/register','Auth\Api\AuthController@register');

Route::post('/show_dtr_list','Auth\Api\AuthController@show_dtr_list');

Route::post('/update','Auth\Api\AuthController@update');

Route::post('/delete','Auth\Api\AuthController@delete');

 });

这就是每当用户成功登录,注册甚至注销其帐户时我都会做出的反应。

return response(['status'=>'oK','message'=>'Successful!']);

我想要的是何时用户每次使用过期的令牌时。 api应该响应这样的

{ "message": "Token is expired" }

不仅仅是

{ "message": "Unathenticated" }

一些线程讨论过,我需要重写laravel的某些功能,但是我不知道我将从何处开始以及如何开始。

4 个答案:

答案 0 :(得分:0)

覆盖auth:api中间件,并进行相应修改以给出所需的响应。

答案 1 :(得分:0)

这是我解决问题的方式。如果您使用的是Laravel 5.5或更高版本,请使用它。然后,您可以使用编辑处理程序文件来覆盖它。
app/Exceptions/Handler.php

在Handler.php文件中调用AuthenticationException use Illuminate\Auth\AuthenticationException;

并在其中添加Under给定功能。

protected function unauthenticated($request, AuthenticationException $exception){
if ($request->expectsJson()) {
   return response()->json(['isAuth'=>false, 'message' => $exception->getMessage()], 401);
}
$guard = array_get($exception->guards(),0);
    switch ($guard) {
        default:
            $login = 'login';
            break;
    }return redirect()->guest(route($login));}

在Json Return中,您可以根据需要添加新参数。 您还可以检查完整的更新后的Handler.php

<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Auth\AuthenticationException;
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.
 *
 * @param  \Exception  $exception
 * @return void
 */
public function report(Exception $exception)
{
    parent::report($exception);
}
/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    return parent::render($request, $exception);
}
protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['isAuth'=>false, 'message' => $exception->getMessage()], 401);
    }
    $guard = array_get($exception->guards(),0);
    switch ($guard) {
        default:
            $login = 'login';
            break;
    }
    return redirect()->guest(route($login));
}
}
?>

答案 2 :(得分:0)

此解决方案对我有用,可以在Laravel Docs中找到。 您可以像这样在Handler中覆盖未经身份验证的函数:

from cassis import *

with open('TypeSystem.xml', 'rb') as f:
  typesystem = load_typesystem(f)

with open('my-text.xmi', 'rb') as f:
  doc = load_cas_from_xmi(f, typesystem=typesystem)

with open('output.txt', 'w') as f:
  for segment in doc.select('webanno.custom.Segment'):
    f.write(f"{segment.get_covered_text()}\t{segment.label}\n")

然后处理并提供所需的响应。

别忘了将其导入到Handle.php文件中:

protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
                ? response()->json(['message' => $exception->getMessage()], 401)
                : redirect()->guest(route('login'));
}

我希望它对您有效!

答案 3 :(得分:0)

1- 创建新的中间件 UserAccessible

 <?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class UserAccessible
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $isAuth = Auth::guard('api')->check();

        if(!$isAuth){
            // redirect page or error.

            $code = 401;

            $output = ['code' => $code,
                'status' => false,
                'msg' => 'Unauthenticated',
                'data' => []];

            return response()->json($output, $code);
        }

        return $next($request);
    }
}

2- 在 Kernal.php 中定义中间件

protected $routeMiddleware = [
    'user_accessible' => \App\Http\Middleware\UserAccessible::class,
];

}

3- 在控制器中

class XController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('user_accessible');
    }

或者在路由中

Route::middleware('user_accessible')->get('/user', function (Request $request) {
    return $request->user();
});