Laravel在不破坏身份验证的情况下加密用户电子邮件


Laravel encrypt user email without breaking authentication

我想在数据库中加密电子邮件地址。使用mutator,我可以为我的laravel网络应用程序加密和解密模型属性。

问题是电子邮件属性用于身份验证。因此,在电子邮件中使用变体似乎完全破坏了我的应用程序,可能是通过Auth::check()、id()、login()等。

我曾考虑编写一个自定义身份验证驱动程序,但无法使其发挥作用。

简单地说,我只想知道在哪里重载模型,以便在set上添加加密,在get上解密,这将与laravels身份验证方法兼容。

除了加密之外,您还需要在自定义Auth提供程序中实现某种盲索引。

有很多方法可以破坏这样的实现。请务必参考CipherSweet文档(尤其是其安全设计和内部结构),以确保您的实现一切正常。

或者,您可以使用CipherSweet为您的自定义Auth提供程序供电,而不用担心自己的加密实现。

我知道为时已晚,但以下是我的实现:不知怎么的,我用一种肮脏的方式处理了这件事。在使用laravel强化之前,我必须首先使用原始查询向用户发送电子邮件,以防止触发模型观察者:

$operator = Operator::query()->whereBlind('email','operator_email_index', strtolower($request['email']))->first();

如果运营商存在,则覆盖电子邮件请求并直接从型号获取电子邮件

if($operator) { $credentials['email'] = DB::table('operator_operators')->where('id',$operator->id)->first()->email; }
and then use the default Auth::Attempt method
$this->guard()->attempt( $credentials, $request->filled('remember') );

但使用enhance,您可以使用authenticateUsing方法轻松覆盖尝试,并防止额外的查询。

这是我的尝试登录功能:

 protected function attemptLogin(Request $request)
{
    $credentials = $this->credentials($request);
    $operator = Operator::query()->whereBlind('email','operator_email_index', strtolower($request['email']))->first();
    if($operator) {
        $credentials['email'] = DB::table('operator_operators')->where('id',$operator->id)->first()->email;
    }
    return $this->guard()->attempt(
        $credentials, $request->filled('remember')
    );
   
}