为什么api路由无法使用Auth :: logout Laravel

问题描述 投票:0回答:1

现在,我正在使用api.php路由从VueJS上的 Axios 发出请求,并且我需要从Auth::guard('web')->logout(); 命令,但目前无法执行此操作。

路线/ api.php

Route::group([ 'prefix' => 'v1/auth', 'middleware' => 'jwt'], function () { //
  Route::get('me', 'Auth\UserController@me');
  Route::get('gg', 'Auth\UserController@test');
});

应用程序/ HTTP / sMiddleware / JwtMiddleware.php

    <?php

namespace App\Http\Middleware;

use Closure;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Auth;

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


        try
        {
            if (! $user = JWTAuth::toUser(JWTAuth::getToken()))
            {
                return response()->json([
                'code'   => 101, // means auth error in the api,
                'response' => 'not authenticate' // nothing to show 
                ]);
            }
        }
        catch (TokenExpiredException $e)
        {
            // If the token is expired, then it will be refreshed and added to the headers
            try
            {
                $refreshed = JWTAuth::refresh(JWTAuth::getToken());
                header('Authorization: Bearer ' . $refreshed);
            }
            catch (JWTException $e)
            {
                return response()->json([
                'code'   => 103, // means not refreshable 
                'response' => 'token jwt exception' // nothing to show 
                ]);
            }
        }
        catch (JWTException $e)
        {

            Auth::guard('web')->logout(); // here

            return response()->json([
                'code'   => 101, // means auth error in the api,
                'response' => 'jwterror' // nothing to show 
            ]);
        }

        return  $next($request);
    }
}

但是当我从api.php迁移到web.php 。 我可以使用Axios发布注销信息

请告诉我如何在api路由文件中使用Auth::logout

对不起,我英语不好。

php laravel authentication laravel-5.6
1个回答
0
投票

注销是通过session driver实现的,与Web Guard不同, API Guard使用的是token driver而不是会话驱动程序。

基本上,用户不是登录到API,而是应用程序的WEB部分。

在api中; 找到一种使令牌失效/失效的方法,以使具有该令牌的用户无法再访问api资源。

try {
   JWTAuth::invalidate($request->input('token'));
   return response()->json(['success' => true, 'message'=> "You have successfully logged out."]);
} catch (JWTException $e) {
   // something went wrong whilst attempting to encode the token
   return response()->json(['success' => false, 'error' => 'Failed to logout, please try again.'], 500);
}

网页登出

会话注销

© www.soinside.com 2019 - 2024. All rights reserved.