【问题标题】:JWT : The token could not be parsed from the requestJWT:无法从请求中解析令牌
【发布时间】:2019-01-14 05:42:17
【问题描述】:

我在控制器中使用 jwt 进行 CRUD,我有产品并希望将 $user_id 保存在数据库中:

  public function store(Request $request)
  {
    $this->user = JWTAuth::parseToken()->authenticate();
    $this->validate($request, [
      'name' => 'required',
      'price' => 'required|integer',
      'quantity' => 'required|integer'
    ]);

    $product = new Product();
    $product->name = $request->name;
    $product->price = $request->price;
    $product->quantity = $request->quantity;
    $product->user_id = $this->user;
    $product->save;

    if ($product)
      return response()->json([
        'success' => true,
        'product' => $product
      ]);
    else
      return response()->json([
        'success' => false,
        'message' => 'Sorry, product could not be added'
      ], 500);
  }

效果很好,但我用过:

$this->user = JWTAuth::parseToken()->authenticate();

在我的一些方法中控制器,所以我想防止重复,并将它写在我的控制器的构造中,但是当我运行时:

php 工匠路线:列表

显示这个错误:

无法从请求中解析令牌

【问题讨论】:

    标签: php laravel authentication jwt


    【解决方案1】:

    您使用的 JWTAuth 版本不能很好地与 Laravel 集成,因此应该避免使用。

    除此之外,你得到这个的原因是你的请求在构造函数被调用时不正确存在。相反,打开你的基本控制器(通常是app/Http/Controllers/Controller)并添加以下方法。

    protected function user() {
        return JWTAuth::parseToken()->authenticate();
    }
    

    这样,只要你想要用户,你就可以$this->user()。

    【讨论】:

    • 我遇到了和上面一样的问题。我用composer require tymon/jwt-auth:dev-develop --prefer-source。你能告诉我我应该调用哪个版本确实与 Laravel 配合得很好?
    猜你喜欢
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 2016-02-28
    • 2023-03-28
    • 2016-02-19
    • 2019-11-21
    • 2017-10-21
    相关资源
    最近更新 更多