首页 文章

Laravel Passport / oauth路线工作但不是/ api

提问于
浏览
0

使用Laravel,Passport和Vue构建应用程序 . 这个问题与使用oAuth2登录无直接关系,而是使用自己的javascript代码来消费受Passport保护的api,如per the docs .

当访问主页并使用axios获取 /oauth 时,我收到错误401,如预期的那样 .

使用laravel提供的默认登录(使用 web auth)登录后,我可以返回主页,并且 /oauth 的axios请求效果很好;例如 /oauth/clients 按预期返回登录用户的客户端 .

mounted() {

    //works as expected: 401 when logged out and response when logged in via /login
    axios.get('/oauth/clients')
          .then(response => {
              console.log(response.data)
          })

    //Always returns 400 error
    axios.get('/api/user')
          .then(response => {
              console.log(response.data)
          })

  }

但是,当我尝试使用axios来获取 /api/user 时,我收到400错误,并显示未经验证的消息(无论是在登录之前还是之后,同样的错误) .

//Returns a 400, always
Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

如果我是正确的, /oauth 路由工作的事实证明laravel_token,csrf和任何此类事情正在正确发送 . 因此,我认为这是服务器方面的问题,尤其是使用auth:api guard . 在auth配置文件中,我将其设置为使用Passport,并遵循所有文档 .

我很困惑为什么我在调用api时得到400错误而不是401,以及为什么它首先不进行身份验证 .

自从according to this video(11:30大关)以来特别令人沮丧,它发挥了作用 .

与Postman相同的行为 .

问:这个错误的解决方案是什么?

完整代码on GitHub .

1 回答

  • -1

    app/Http/Kernel.php 中添加此代码

    'web' => [
        // Other middleware...
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
    ],
    

相关问题