【问题标题】:Can't get auth user with laravel passport, keep getting "Unauthenticated" error无法使用 laravel 护照获取身份验证用户,不断收到“未经身份验证”错误
【发布时间】:2019-08-28 00:06:02
【问题描述】:

我无法通过 JWT 和 vue 在 Laravel 护照应用中获取经过身份验证的用户的信息。

我已经安装了 laravel 护照。我已经完成了文档中的所有内容并添加了:

\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,

将它与 js 一起用于 SPA 应用程序。

我已经使用 auth:api 中间件保护了我的路由,但我不断收到:

{"Status":{"api_status":0,"Code":401,"Message":"Unauthenticated"}}

当我使用邮递员在授权承载令牌中手动插入 CSRF-TOKEN 时。它确实给了我身份验证用户。

无论我做什么,我总是在 Auth::user();在我的控制器和路由中

Laravel V5.7 节点 V10.15.3 Npm V.6.9.0

【问题讨论】:

    标签: laravel authentication vuejs2 jwt


    【解决方案1】:

    您需要发送一个 POST 请求(使用 Postman/Insomnia),其中包含您要登录到您应用中的 /oauth/token 的用户的详细信息,这将使用 API 令牌进行响应。您将此 api 令牌保存在本地,然后将其作为 Header 变量添加到您的 guzzle/axios/whatever 函数的 http 调用(每一个!)到您的 API。

    $http = new GuzzleHttp\Client;
    $data = 'Whatever';
    $response = $http->request('POST','api/user',[
        'data' => $data,
        'headers' => [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer xxxxxxxxxxxxThis is the long authentication string returned from the Postman requestxxxxxxxxxxxxxx'
        ]
    ]);
    dd(json_decode((string) $response->getBody())); // To view the response
    

    发件人:https://laravel.com/docs/5.5/passport#creating-a-password-grant-client

    【讨论】:

    • 这就是 kernel.php 中的 CreateFreshApiToken 类的用途,这样护照就会从 CSRF-Token 中获取授权。
    • 以上是通过调用API授权用户,而不是使用应用的登录表单
    猜你喜欢
    • 2019-06-14
    • 2018-05-02
    • 2017-01-06
    • 2019-02-28
    • 2017-04-24
    • 2018-09-01
    • 1970-01-01
    • 2018-11-13
    • 2019-03-08
    相关资源
    最近更新 更多