简体   繁体   English

如何在 LUMEN (Laravel 6.2) 中使用 GATE 门面

[英]How to use GATE facades in LUMEN (Laravel 6.2)

I'm trying to create an ACL with Lumen.我正在尝试使用 Lumen 创建 ACL。 I want to use the built-in gates/policies to do so.我想使用内置的门/策略来做到这一点。 I've been following the official Lumen Docs: https://lumen.laravel.com/docs/6.x/authorization我一直在关注官方 Lumen Docs: https : //lumen.laravel.com/docs/6.x/authorization

and Laravel Docs: https://laravel.com/docs/6.x/authorization和 Laravel 文档: https ://laravel.com/docs/6.x/authorization

to do so.这样做。 They say I need to register both facades and the gate facade in order to use Gates.他们说我需要注册 Facades 和 Gate facade 才能使用 Gates。

I have the following code inside my AuthServiceProvider.php:我的 AuthServiceProvider.php 中有以下代码:

<?php

namespace App\Providers;

use App\User;
use Firebase\JWT\JWT;
use Illuminate\Support\ServiceProvider;

use Illuminate\Support\Facades\Gate;
//use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Http\Request;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Boot the authentication services for the application.
     *
     * @return void
     */
     public function boot()
     {
       // Here you may define how you wish users to be authenticated for your Lumen
       // application. The callback which receives the incoming request instance
       // should return either a User instance or null. You're free to obtain
       // the User instance via an API token or any other method necessary.

       $this->app['auth']->viaRequest('api', function ($request) {
         $key = 'pawifjopawiejfpoaiwejfpoji';
         $jwt = preg_replace('/^Bearer (.*)/', '$1', $request->header('Authorization'));
         $decoded = JWT::decode($jwt, $key, ['HS256']);

         return User::where('email', $decoded->email)->first();
       });

       $this->registerPolicies();

       Gate::define('edit-settings', function($user){
         return $user->isAdmin;
       });
     }
}

And I have the bootstrap/app.php set like so, with $app->withFacades() uncommented:我的 bootstrap/app.php 设置如下, $app->withFacades()注释:

<?php

require_once __DIR__.'/../vendor/autoload.php';

(new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables(
    dirname(__DIR__)
))->bootstrap();

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application(
    dirname(__DIR__)
);

 $app->withFacades();

 $app->withEloquent();

/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/

// $app->middleware([
//     App\Http\Middleware\ExampleMiddleware::class
// ]);

 $app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
   ]);

/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/

// $app->register(App\Providers\AppServiceProvider::class);
 $app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);

/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/

$app->router->group([
    'namespace' => 'App\Http\Controllers',
], function ($router) {
    require __DIR__.'/../routes/web.php';
});

return $app;

And when I now run any http-request with RESTClient (www.restclient.net) against my Lumen API, I get the following error:现在,当我针对 Lumen API 使用 RESTClient (www.restclient.net) 运行任何 http 请求时,出现以下错误:

Call to undefined method App\Providers\AuthServiceProvider::registerPolicies()

I googled quite a lot on this issue and found some solutions, but none of them worked for me.我在这个问题上搜索了很多,并找到了一些解决方案,但没有一个对我有用。 Please help请帮忙

Your provider doesn't have that method.您的提供商没有这种方法。 This is the entire AuthServiceProvider that Laravel uses as its base for AuthServiceProvider :这是整个AuthServiceProvider是Laravel使用它作为基地AuthServiceProvider

use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [];

    /**
     * Register the application's policies.
     *
     * @return void
     */
    public function registerPolicies()
    {
        foreach ($this->policies() as $key => $value) {
            Gate::policy($key, $value);
        }
    }

    /**
     * Get the policies defined on the provider.
     *
     * @return array
     */
    public function policies()
    {
        return $this->policies;
    }
}

registerPolicies isn't doing anything special. registerPolicies没有做任何特别的事情。 It just spins through $policies and registers them;它只是遍历$policies并注册它们; you can do this yourself.你可以自己做。

"Unlike Laravel, Lumen does not have a $policies array on its AuthServiceProvider . However, you may still call the policy method on the Gate facade from within the provider's boot method" - Lumen 6.x Docs - Authorization - Defining Policies “不像Laravel,流明没有一个$policies在其阵列AuthServiceProvider但是,您仍可以调用。 policy上的法Gate门面从供应商的内boot方法” -流明6.x的文档-授权-定义策略

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM