【问题标题】:Laravel Passport API return UnauthenticatedLaravel Passport API 返回未经身份验证
【发布时间】:2021-09-21 11:19:10
【问题描述】:

我正在尝试在我的 laravel 应用程序中验证 api 调用。我已经按照文档安装了 Passport,我想我没有错过任何东西。但 API 调用返回 401 Unauthenticated。

Auth.php

 'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
        'hash' => false,
    ],
],

AuthServiceProvider.php

 public function boot() {

    $this->registerPolicies();
    Passport::tokensExpireIn(now()->addMinutes(config('auth.token_expiration.token')));
    Passport::refreshTokensExpireIn(now()->addMinutes(config('auth.token_expiration.refresh_token')));

}

RouteServiceProvider

    $this->configureRateLimiting();

    $this->routes(function () {
        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));

        Route::middleware('web')
            ->namespace($this->namespace)
            ->group(base_path('routes/web.php'));
    });

标题

和 .htaccess

 RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

【问题讨论】:

  • 尝试在邮递员的授权中添加token>Bearer Token而不是header直接运行composer dump autoload命令
  • @HuzaifaQidwai 我尝试了,但显示消息:尚未验证

标签: laravel laravel-passport


【解决方案1】:

看来您需要注册必要的路由来发布令牌。很简单,你在boot 方法中调用Passport::routes 方法。

 public function boot() {

    $this->registerPolicies();
    Passport::routes();
    Passport::tokensExpireIn(now()->addMinutes(config('auth.token_expiration.token')));
    Passport::refreshTokensExpireIn(now()->addMinutes(config('auth.token_expiration.refresh_token')));

}

如果你有任何问题,请告诉我。

【讨论】:

  • @Maryam 我很高兴。我的回答很有用。
【解决方案2】:

将此代码添加到根文件夹的 .htaccess 中(不仅在公用文件夹内)

RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Official documents refer

Read more here

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
  • @learner_323 现在,我尝试一下并将此代码添加到 .htaccess 根目录,但无法正常工作并再次显示未经身份验证
猜你喜欢
  • 2018-01-05
  • 2018-08-12
  • 1970-01-01
  • 2020-03-15
  • 2017-04-24
  • 2019-10-07
  • 2019-06-14
  • 2018-07-20
  • 1970-01-01
相关资源
最近更新 更多