护照授权不会在 Laravel 8 中授权用户

时间:2021-05-09 06:27:05

标签: php laravel laravel-8

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

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']);
});

现在我可以在 Postman 上正确发送请求并注册新用户并获得 api_token

但是当我在 /comment url 上发送 POST 请求,并且还添加这样的标题时:

enter image description here

我收到这条消息:

{
    "message": "Unauthenticated."
}

表示用户尚未通过身份验证。但是,正如您在图片中看到的,我已将 api_tokenBearer 正确添加为 Authorization

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

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

提前致谢。

用户模型:

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();

        //
    }
}

0 个答案:

没有答案