Laravel Passport 使用密码授权方式小窍门
之前项目接口验证一直在使用 jwt-auth ,今天去 Github 上了下了,这个项目已经有1年没有更新了,作者有可能比较忙,没有经历来维护这个项目了,积累了30多个 PR 没有合并。
现在PHP8已经是主流了,Laravel 也要升级到 9 了,所以决定使用 Laravel Passport 来为接口做授权验证。目前只有小程序和APP来使用接口,所以用了密码授权方式来做整体验证。
小程序要使用 openid 进行自动登录,不需要用户密码,看了下 Passport 文档,找到了 findForPassport
和 validateForPassportPasswordGrant
方法来自定义,但这样就会比较麻烦,要定义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();
}
不得不说,这种设计真的很不错,支持各种自定义,还是要多学习多看源码。
推荐文章: