简体   繁体   中英

Creating Multiple Auth Providers in Lumen

I am trying to create multiple Auth Guards and services for my API. I want specific group to be available to specific users (more like RBAC without sessions).

If a user tries to access a group that has admin:auth as middleware its privileges will be checked. If it has api:auth then no privilege check.

I can't understand how to do this. I have added the following lines in the bootstrap/app.php

$app->routeMiddleware([
    'admin' => App\Http\Middleware\Admin::class,
    'api' => App\Http\Middleware\Api::class,
]);

And:

$app->register(App\Providers\AdminServiceProvider::class);
$app->register(App\Providers\ApiServiceProvider::class);

and created the Files Admin.php and APi.php in Middleware folder with the following content (basically same as Authenticate.php with name changes)

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;

class Admin
{
    /**
     * The authentication guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if ($this->auth->guard($guard)->guest()) {
            return response('Unauthorized.', 401);
        }

        return $next($request);
    }
}

And the AdminServiceProvider and ApiServiceProvider in the App\\Providers folder with just this in function boot() :

var_dump($this->app['api']);exit;

And this on top:

namespace App\Providers;

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

class ApiServiceProvider extends ServiceProvider

But I get the Following Error:

错误

What am I missing? I have already done composer dump-autoload , no difference.

Regards

Well what I ended up using is more like a work around, but I think this might be how it is supposed to be used.

So what I did was that I created two groups (a parent and a child) with the middlewares I needed as follows:

$app->group(["middleware" => "middleware1"], function() use ($app){
  $app->group(["middleware" => "middleware1"], function() use ($app){
    $app->post("/signin", "AppController@signin");
  }
}

This way, the signin route is reached after going through 2 middlewares.

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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