Custom Laravel Passport Check

只谈情不闲聊 提交于 2019-12-06 04:42:17
Seakleng Say

I hope this answer can help to other.
If you want to add variable and pass this variable to findPassport function in User Authenticate model , you need to update 3 class in passport :
  - UserRepositoryInterface in vendor\league\oauth2-server\src\Repositories\UserRepositoryInterface
  - PasswordGrant in vendor\league\oauth2-server\src\Grant\PasswordGrant
  - UserRepository in vendor\laravel\passport\src\Bridge\UserRepository

in the example code I will add parent variable and code will look like this

+in UserRepositoryInterface class

interface UserRepositoryInterface extends RepositoryInterface
{

/**
 * Get a user entity.
 *
 * @param string                $username
 * @param string                $password
 * @param string                $grantType    The grant type used
 * @param ClientEntityInterface $clientEntity
 *
 * @return UserEntityInterface
 */
public function getUserEntityByUserCredentials(
    $username,
    $password,
    $parent,                           <------variable example 
    $grantType,
    ClientEntityInterface $clientEntity
);
}

+in PasswordGrant class

class PasswordGrant extends AbstractGrant{ 
protected function validateUser(ServerRequestInterface $request, ClientEntityInterface $client)
{
    $username = $this->getRequestParameter('username', $request);
    if (is_null($username)) {
        throw OAuthServerException::invalidRequest('username');
    }

    $password = $this->getRequestParameter('password', $request);
    if (is_null($password)) {
        throw OAuthServerException::invalidRequest('password');
    }

  /**
  * Get a user parent.
  * varaible example 
  */
    $parent = $this->getRequestParameter('parent', $request);  
    if (is_null($parent)) {
        throw OAuthServerException::invalidRequest('password');
    }

    $user = $this->userRepository->getUserEntityByUserCredentials(
        $username,
        $password,
        $parent,                          <--- variable example get from request
        $this->getIdentifier(),
        $client
    );
    if ($user instanceof UserEntityInterface === false) {
        $this->getEmitter()->emit(new RequestEvent(RequestEvent::USER_AUTHENTICATION_FAILED, $request));

        throw OAuthServerException::invalidCredentials();
    }

    return $user;
}  }

+in UserRepository class

class UserRepository implements UserRepositoryInterface
{

public function getUserEntityByUserCredentials($username, $password, $parent, $grantType, ClientEntityInterface $clientEntity) 
/*add 1more parameter that implement from UserRepositoryInterface*/
{
    $provider = config('auth.guards.api.provider');

    if (is_null($model = config('auth.providers.'.$provider.'.model'))) {
        throw new RuntimeException('Unable to determine authentication model from configuration.');
    }

    if (method_exists($model, 'findForPassport')) {
        $user = (new $model)->findForPassport($username,$parent);    <--- finally we pass parent variable to findForPassport here
    } else {
        $user = (new $model)->where('email', $username)->first();
    }

    if (! $user) {
        return;
    } elseif (method_exists($user, 'validateForPassportPasswordGrant')) {
        if (! $user->validateForPassportPasswordGrant($password)) {
            return;
        }
    } elseif (! $this->hasher->check($password, $user->getAuthPassword())) {
        return;
    }

    return new User($user->getAuthIdentifier());
}
}

then u can get $parent value from parameter in findForPassport .but make sure you return value as eloquent User .if you want to join table , you can look my example code below

class User extends Authenticatable{

..........
public function findForPassport($identifier,$parent) {
    $a = $this
        ->Join('role as r', 'r.user_id', '=', 'users.id')
        ->get();
    return $a->where('name', $identifier)->where('role_id',$parent)->first();

  }
}

From the link to passport issue #81 pointed by @Arun in OP:

There's probably a better way of doing this now but I extended the PassportServiceProvider and copied the registerAuthorizationServer function so that I could register my own grant type.

Swap out the provider in config\app.php with your new one:

'providers' => [
 //Laravel\Passport\PassportServiceProvider::class,
    App\Providers\PassportClientCredentialsServiceProvider::class,

Updated registerAuthorizationServer function that includes new grant option:

protected function registerAuthorizationServer()
  {
    parent::registerAuthorizationServer();
    $this->app->singleton(AuthorizationServer::class, function () {
      return tap($this->makeAuthorizationServer(), function ($server) {
        /**
         * @var $server AuthorizationServer
         */
        $server->enableGrantType(
          new ClientCredentialsGrant(), Passport::tokensExpireIn()
        );
        /** custom grant type */
        $server->enableGrantType(
          new PasswordOverrideGrant(
            $this->app->make(UserRepository::class),
            $this->app->make(RefreshTokenRepository::class)
          ), Passport::tokensExpireIn()
        );

        $server->enableGrantType(
          $this->makeAuthCodeGrant(), Passport::tokensExpireIn()
        );

        $server->enableGrantType(
          $this->makeRefreshTokenGrant(), Passport::tokensExpireIn()
        );

        $server->enableGrantType(
          $this->makePasswordGrant(), Passport::tokensExpireIn()
        );

        $server->enableGrantType(
          new PersonalAccessGrant(), new \DateInterval('P1Y')
        );
      });
    });
  }

PasswordOverrideGrant looks like this:

<?php

namespace App\Auth;

use App\User;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Grant\PasswordGrant;
use League\OAuth2\Server\RequestEvent;
use Psr\Http\Message\ServerRequestInterface;

class PasswordOverrideGrant extends PasswordGrant
{
  protected function validateUser(ServerRequestInterface $request, ClientEntityInterface $client)
  {
    $username = $this->getRequestParameter('username', $request);
    if (is_null($username)) {
      throw OAuthServerException::invalidRequest('username');
    }

    $custom_hash_token = $this->getRequestParameter('hash_token', $request);
    if (is_null($custom_hash_token)) {
      throw OAuthServerException::invalidRequest('identifier');
    }

    $credentials = [
      'username' => $username,
      'hash_token' => $custom_hash_token,
    ];

    $user = User::where($credentials)->first();

    if ($user instanceof User === false) {
      $this->getEmitter()->emit(new RequestEvent(RequestEvent::USER_AUTHENTICATION_FAILED, $request));

      throw OAuthServerException::invalidCredentials();
    }

    return $user;
  }
  public function getIdentifier()
  {
    return 'password_override';
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!