0

目前我正在使用 JWT Auth 开发 Laravel 5.8,一切都在 Postman 中运行,但是当我尝试在浏览器上进行测试时,我遇到了很多错误,并且已经一一修复。现在,当我尝试使用 Request 传递 JSON Web Token 时出现另一个错误。未正确提供令牌。在我登录过程之后:

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方法中,成功生成了token,但是在index我无法访问token。感谢您的关注。

4

1 回答 1

0

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

于 2019-04-18T12:35:57.867 回答