简体   繁体   English

Laravel Passport API 调用总是返回 Unauthenticated

[英]Laravel Passport API call always return Unauthenticated

So I have setup my API with Passport and tried to make GET request for almost a week now but still getting the response bellow :所以我已经用 Passport 设置了我的 API,并尝试发出 GET 请求将近一个星期,但仍然得到以下响应:

{
"message": "Unauthenticated."
}

Below are my configuration :以下是我的配置:

Auth.php验证文件

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

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

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

AuthServiceProvider.php AuthServiceProvider.php

public function boot()
{
    $this->registerPolicies();

    //
    Passport::routes();
    Passport::tokensExpireIn(Carbon::now()->addDays(7));

   Passport::refreshTokensExpireIn(Carbon::now()->addDays(14));



}

RouteServiceProvider路由服务提供者

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

Controller : Token request function using user credentials as per laravel doc控制器:根据laravel 文档使用用户凭据的令牌请求功能

public function callback(Request $request)
{
     $http = new Client();
    $token_url=url('oauth/token');

$response = $http->post($token_url, [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => $this->client_id,
        'client_secret' => $this->client_secret,
        'username'=>'my-username',
        'password'=>'my-password',
        'scope' =>'*',
    ],
]);

return json_decode((string) $response->getBody(), true);
}

Which returns an access_token that I use in my request in my request .它返回我在请求中使用的 access_token 。 I tried all the solution listed below and none of them worked :我尝试了下面列出的所有解决方案,但都没有奏效:

.htaccess .htaccess

# Handle Authorization Header
 RewriteCond %{HTTP:Authorization} .
 RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Passport.php line 167 Passport.php 第 167 行

 public static function tokensExpireIn(DateTimeInterface $date = null)
{
    if (is_null($date)) {
        return static::$tokensExpireAt
                        ? Carbon::now()->diff(static::$tokensExpireAt)
                        : new DateInterval('P1Y');
    }

    static::$tokensExpireAt = $date;

    return new static;
}

Please help , I'm desperate now :)请帮忙,我现在很绝望:)

The problem is how you authenticate and which token you are using.问题在于您如何进行身份验证以及您使用的是哪个令牌。

There are 2 ways to generate token有两种生成token的方法

  1. Users login and you use create token to get the token if user is authenticated.用户登录,如果用户通过身份验证,您可以使用创建令牌来获取令牌。
  2. Generate a client and use PRE built routes by passport to get token生成一个客户端,并通过passport使用PRE构建的路由来获取token

Now in the API routes you have to tell in your method how you are authenticating for example现在,在 API 路由中,您必须在方法中说明您是如何进行身份验证的,例如

// Below one is for authenticating Client token  
Route::get('/test', 'Api\TestController@index')->middleware('client_credentials');
// Below one is for the User token  
Route::get('/test', 'Api\TestController@index')->middleware('auth:api');

And Remember if you are using client authentication, you have to add the below line in routemiddleware in App/http/kernel.php请记住,如果您使用客户端身份验证,则必须在App/http/kernel.php routemiddleware中添加以下行

'client_credentials' => \\Laravel\\Passport\\Http\\Middleware\\CheckClientCredentials::class

I hope that solves issues我希望能解决问题

Try creating a new password grant client with:尝试使用以下命令创建新的密码授予客户端:

php artisan passport:client --password

You'll get an output like:你会得到如下输出:

What should we name the password grant client? [Laravel Password Grant Client]:
 > 

Password grant client created successfully.
Client ID: 4
Client secret: WlRYEbA5lt5esbi0MuFyJPzPDmHDGsk3iC5QGw7d

Use those credentials to fill your client id and secret.使用这些凭据填写您的客户端 ID 和密码。 Standard client credentials created through the Vue component interface do not work for password grants.通过 Vue 组件接口创建的标准客户端凭据不适用于密码授予。

try to comment middlewares in api middleware group (app/HTTP/Kernel.php)尝试在 api 中间件组 (app/HTTP/Kernel.php) 中评论中间件

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
        ],

        'api' => [
//            'throttle:60,1',
//            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

Or comment api middleware group in app/Providers/RouteServiceProvider.php或者在 app/Providers/RouteServiceProvider.php 中注释 api 中间件组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Laravel 5.7护照返回始终在AWS服务器上未经身份验证 - Laravel 5.7 passport return Unauthenticated always on AWS server 总是收到“消息”:“未经身份验证”。 - Laravel 护照 - Always got "message": "Unauthenticated." - Laravel Passport Laravel Passport身份验证问题:始终返回未经身份验证的 - Laravel Passport Authentication Issues: Always returns unauthenticated Laravel 5.8 护照在本地工作但在 ['middleware' => 'auth:api'] 组中的路由时未经身份验证返回 - Laravel 5.8 passport working in local but in sever return unauthenticated when routes in ['middleware' => 'auth:api'] group Laravel 5.5.45未经验证的护照 - Laravel 5.5.45 Unauthenticated with passport Laravel 未认证护照 - Laravel Unauthenticated passport laravel护照返回未经认证 - laravel passport returns unauthenticated PHP Laravel Passport OAuth2在受保护的路由上始终返回未经身份验证的状态 - PHP Laravel Passport OAuth2 Always returns Unauthenticated on a Protected Route 使用个人访问令牌在 Postman 中未经身份验证的 Laravel 5.3 Passport API - Laravel 5.3 Passport API unauthenticated in Postman using personal access tokens Laravel Passport 使用自己的 API 和 Axios 401 未认证 - Laravel Passport Consuming own API with Axios 401 Unauthenticated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM