Laravel Passport 使用密码授权方式小窍门

之前项目接口验证一直在使用 jwt-auth ,今天去 Github 上了下了,这个项目已经有1年没有更新了,作者有可能比较忙,没有经历来维护这个项目了,积累了30多个 PR 没有合并。

现在PHP8已经是主流了,Laravel 也要升级到 9 了,所以决定使用 Laravel Passport 来为接口做授权验证。目前只有小程序和APP来使用接口,所以用了密码授权方式来做整体验证。

小程序要使用 openid 进行自动登录,不需要用户密码,看了下 Passport 文档,找到了 findForPassportvalidateForPassportPasswordGrant 方法来自定义,但这样就会比较麻烦,要定义2个方法,而且 validateForPassportPasswordGrant 也没有任何有意义的代码,直接返回了 true ,在源码的时候。

无意间看到了 findAndValidateForPassport 方法,这下就方便多了,代码也更容易理解。

变更前:自定义用户名字段及密码验证

/**
 * Find the user instance for the given username. * * @param string $openId
  * @return mixed
 */
public function findForPassport(string $openId): mixed
{
  // 匹配公众号和小程序openid
  return $this->where('open_id', $openId)
 ->orWhere('mp_open_id', $openId)->first();
}

/**
 * Validate the password of the user for the Passport password grant. * * @param string $password
  * @return bool
 */
public function validateForPassportPasswordGrant(string $password): bool
{
  // 小程序端无需密码验证 固定返回 true  
  return true;
}

变更后:自定义用户名字段及密码验证

/**
  * Passport 授权验证
  *
  * @description 使用用户名/密码方式进行验证,因为目前只需支持小程序端使用,可通过openid自动登录无需验证密码
  * @param $openId
  * @param $password
  * @return mixed
  */
  public function findAndValidateForPassport($openId, $password): mixed
  {
     return $this->where('open_id', $openId)
          ->orWhere('mp_open_id', $openId)->first();
  }

不得不说,这种设计真的很不错,支持各种自定义,还是要多学习多看源码。

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 7

弱弱的准备去看一下 findAndValidateForPassport 我还自定义了直连,没有通过 Http去认证。调试有时候不好调

2年前 评论
24K大白羊 (楼主) 2年前

不做 Open Api 其实没必要用 Passport, 如果只是作为一个认证 Token 的话, 用 Client 模式就足够了, 在如果只是为了认证, 使用 Sanctum 会轻量许多

2年前 评论
24K大白羊 (楼主) 2年前

@24K大白羊 大佬,我想请教下您是怎么处理token有效期验证以及刷新token的?我也用的laravel9。

1年前 评论
24K大白羊 (楼主) 1年前

就是说 如果密码授权的方式( 'grant_type' => 'password') auth的时候会走 findAndValidateForPassport 吗

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!