Multi Auth with Laravel 5.4 and Passport

后端 未结 7 2085
猫巷女王i
猫巷女王i 2020-12-31 20:46

I am trying to setup multi auth with Laravel Passport, but it doesn\'t seem to support it. I am using the Password Grant to issue tokens which requires me to pass username/p

相关标签:
7条回答
  • 2020-12-31 21:37

    I have created a small package for this issue. Here's the link for the complete doc link

    But the gist is, whenever a user entity gets logged in, it checks for the guards and providers.

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    
        'customers' => [
            'driver' => 'passport',
            'provider' => 'customers'
        ],
    ],
    
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => 'App\User',
        ],
        /**
         * This is the important part. You can create as many providers as you like but right now, 
         * we just need the customer
         */
         'customers' => [
             'driver' => 'eloquent',
             'model' => 'App\Customer',
         ],
    ],
    

    You should have a controller like this:

    <?php
    
    namespace App\Http\Controllers\Auth;
    
    use App\Customers\Customer;
    use App\Customers\Exceptions\CustomerNotFoundException;
    use Illuminate\Database\ModelNotFoundException;
    use Laravel\Passport\Http\Controllers\AccessTokenController;
    use Laravel\Passport\TokenRepository;
    use League\OAuth2\Server\AuthorizationServer;
    use Psr\Http\Message\ServerRequestInterface;
    use Lcobucci\JWT\Parser as JwtParser;
    
    class CustomerTokenAuthController extends AccessTokenController
    {
         /**
          * The authorization server.
          *
          * @var \League\OAuth2\Server\AuthorizationServer
          */
         protected $server;
    
         /**
          * The token repository instance.
          *
          * @var \Laravel\Passport\TokenRepository
          */
         protected $tokens;
    
         /**
          * The JWT parser instance.
          *
          * @var \Lcobucci\JWT\Parser
          */
         protected $jwt;
    
         /**
          * Create a new controller instance.
          *
          * @param  \League\OAuth2\Server\AuthorizationServer  $server
          * @param  \Laravel\Passport\TokenRepository  $tokens
          * @param  \Lcobucci\JWT\Parser  $jwt
          */
         public function __construct(AuthorizationServer $server,
                                     TokenRepository $tokens,
                                     JwtParser $jwt)
         {
             parent::__construct($server, $tokens, $jwt);
         }
    
         /**
          * Override the default Laravel Passport token generation
          *
          * @param ServerRequestInterface $request
          * @return array
          * @throws UserNotFoundException
          */
         public function issueToken(ServerRequestInterface $request)
         {
             $body = (parent::issueToken($request))->getBody()->__toString();
             $token = json_decode($body, true);
    
             if (array_key_exists('error', $token)) {
                 return response()->json([
                     'error' => $token['error'],
                     'status_code' => 401
                 ], 401);
             }
    
            $data = $request->getParsedBody();
    
            $email = $data['username'];  
    
            switch ($data['provider']) {
                case 'customers';
    
                    try {
    
                     $user = Customer::where('email', $email)->firstOrFail();
    
                    } catch (ModelNotFoundException $e) {
                      return response()->json([
                          'error' => $e->getMessage(),
                          'status_code' => 401
                      ], 401);
                    }
    
                    break;
    
                default :
    
                    try {
    
                     $user = User::where('email', $email)->firstOrFail();
    
                    } catch (ModelNotFoundException $e) {
                      return response()->json([
                          'error' => $e->getMessage(),
                          'status_code' => 401
                      ], 401);
                    }        
            }
    
            return compact('token', 'user');
        }
    }
    

    and the request should be:

    POST /api/oauth/token HTTP/1.1
    Host: localhost
    Content-Type: application/x-www-form-urlencoded
    Cache-Control: no-cache
    
    grant_type=password&username=test%40email.com&password=secret&provider=customers
    

    To check in your controller who is the logged in user, you can do:

    auth()->guard('customers')->user()

    0 讨论(0)
提交回复
热议问题