JWT Auth错误:无法从请求中解析令牌

时间:2019-04-18 12:31:34

标签: php laravel jwt-auth

当前,我正在使用JWT Auth开发Laravel 5.8,所有功能在Postman中都运行良好,但是当我尝试在Browser上进行测试时,我遇到了很多错误,并且一个一个地修复了。现在,当我尝试使用Request传递JSON Web令牌时,出现另一个错误。令牌提供不正确。在完成登录过程后:

public function signin(Request $request)
  {
    $this->validate($request, [
      'username' => 'required',
      'password' => 'required'
    ]);
    // grab credentials from the request
    $credentials = $request->only('username', 'password');
    try {

        // attempt to verify the credentials and create a token for the user
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json([
              'error' => 'Invalid Credentials, username and password dismatches. Or username may not registered.',
              'status' => '401'
            ], 401);
        }
    } catch (JWTException $e) {
        // something went wrong whilst attempting to encode the token
        return response()->json(['error' => 'could_not_create_token'], 500);
    }
    return response()->json([
      'token'   => $token
    ]);
  }

令牌已成功生成。但是当我需要另一个控制器的令牌时,令牌生成失败,这种方法就是一个例子:

  public function index(Request $request)
  {
    // this will set the token on the object
    JWTAuth::parseToken();
    // and you can continue to chain methods
    $user = JWTAuth::parseToken()->authenticate();
    $token = JWTAuth::getToken();
    die($token);
    try {
        if (! $user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['user_not_found'], 404);
        }
    } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
        return response()->json(['token_expired'], $e->getStatusCode());
    } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
        return response()->json(['token_invalid'], $e->getStatusCode());
    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
        return response()->json(['token_absent'], $e->getStatusCode());
    }

每次我都想JWTAuth::parseToken();遇到此错误:

  

无法从请求中解析令牌

那为什么会这样呢?那我该怎么办?因为在signin方法中,令牌已成功生成,但是在index中,我无法访问令牌。感谢您的关注。

1 个答案:

答案 0 :(得分:0)

令牌需要在每个api请求中通过标头传递 Header Name: Authorization Expected Value: Bearer --token-- (当然没有)