代码之家  ›  专栏  ›  技术社区  ›  parastoo

JWT:无法从请求中分析令牌

  •  1
  • parastoo  · 技术社区  · 7 年前

    我在控制器中使用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();

    在controller中的一些方法中,我希望防止重复,并将其写入controller的构造中,但是当我运行时:

    php artisan路径:列表

    显示此错误:

    无法从请求中分析令牌

    1 回复  |  直到 7 年前
        1
  •  2
  •   ollieread    7 年前

    您正在使用的JWTAuth版本没有很好地与Laravel集成,因此应该避免使用它。

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

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

    这样无论何时你想要用户,你都可以 $this->user() .

    推荐文章