护照授权未授权Laravel 8中的用户 [英] Passport Authorization Does Not Authorize User In Laravel 8

查看:90
本文介绍了护照授权未授权Laravel 8中的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 8和Passport for API.目前,我有这条路线:

I'm working with Laravel 8 and Passport for API. And currently I have this route:

Route::prefix('v1')->group(function(){
    Route::post('login', [\App\Http\Controllers\Api\v1\UserController::class, 'login']);
    Route::post('register', [\App\Http\Controllers\Api\v1\UserController::class, 'register']);

    Route::middleware('auth:api')->group(function() {
        Route::get('/user' , function () {
            return auth()->user();
        });
        Route::post('/comment' , [\App\Http\Controllers\Api\v1\CommentController::class, 'store']);
});

现在,我可以在邮递员上正确发送请求并注册一个新用户,并获取 api_token .

Now I can correctly send a request on Postman and register a new user and gets the api_token.

但是当我在/comment 网址上发送POST请求时,还添加了以下标头:

But when I send a POST request on /comment url, and also adding the Headers like this:

我收到此消息:

{
    "message": "Unauthenticated."
}

表示该用户尚未经过身份验证.但是,正如您在图片中看到的那样,我已正确添加 api_token Bearer 作为 Authorization .

Meaning that the user is not yet authenticated. However as you can see in the picture, I have properly added the api_token with Bearer as Authorization.

那么这里出了什么问题?我该如何解决这个问题?

So what is going wrong here? How can I solve this issue?

我真的很感谢你们的任何想法或建议...

I would really appreciate any idea or suggestion from you guys...

谢谢.

用户模型:

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'api_token'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'api_token'
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

AuthServiceProvider:

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
    }
}

推荐答案

设置步骤安装护照:

composer require laravel/passport
php artisan migrate
php artisan passport:install

向用户模型添加特征:

使用HasApiTokens,HasFactory,可通知;

设置 AuthServiceProvider (您缺少此步骤):

Setup AuthServiceProvider (You're missing this step):

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        
        // MISSING HERE
        if (!$this->app->routesAreCached()) {
            Passport::routes();
        }
    }
}

要添加到答案中,如果您要获得带有密码授权的令牌,请添加.这些是步骤:

To add to the answer, in your case if you want to get a token with a password grant. These are the steps:

  1. 创建客户

php artisan passport:client --password

  1. 获取客户端ID和机密,然后在邮递员在此端点 http://yourapp.com/oauth/token 上向您的应用发出请求,并提供有效载荷:
  1. Get the client id and secret, then make a request in your postman to your app at this endpoint http://yourapp.com/oauth/token, and payload:

{
    'grant_type': 'password',
    'client_id': 'client-id',
    'client_secret': 'client-secret',
    'username': 'myusername@email.com',
    'password': 'my-password',
    'scope': '*',
}

  1. 然后,您可以使用从护照返回的 access_token 来请求您的api
  1. Then you can use your access_token returned from passport to request to your api

这篇关于护照授权未授权Laravel 8中的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆