【问题标题】:JWT Auth Error : The token could not be parsed from the requestJWT Auth 错误:无法从请求中解析令牌
【发布时间】:2019-04-22 18:07:58
【问题描述】:

目前我正在使用 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。感谢您的关注。

【问题讨论】:

  • 您如何在请求中发送令牌?
  • 通过在ajax POST中添加headers:{'Authorization' : 'Bearer ' jwtoken }
  • 你能在你做这个的地方发布你的 JavaScript 的 sn-p 吗?

标签: php laravel jwt-auth


【解决方案1】:

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

【讨论】:

  • 如何从我的登录方法中传递它?
猜你喜欢
  • 2017-01-06
  • 2016-02-28
  • 2019-01-14
  • 2021-10-18
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2016-02-19
  • 2019-12-25
相关资源
最近更新 更多