首页 > 解决方案 > 如何同时使用 MD5 和 Bcrypt 哈希登录 laravel

问题描述

我有一个数据库,其中存储的密码使用 MD5 进行散列。

现在我需要做一些步骤:

1.用户登录(使用bcrypt)

2.If(login failed)进入step3
else登录退出

3.用户登录(使用MD5)

4.If(login success){ 通过bcrypt更新DataBase中的哈希密码。}

结尾

所以我的系统在登录时需要检查MD5和bcrypt,

我怎样才能做到这一点?

标签: phplaravellaravel-5hashmd5

解决方案


您可以使用自己的身份验证方法轻松完成此操作,如 laravel 文档中所述: https ://laravel.com/docs/5.8/authentication#authenticating-users

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class YourCustomController extends Controller
{
    /**
     * Handle an authentication attempt.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return Response
     */
    public function login(Request $request)
    {
        if (Auth::attempt($request->only('email', 'password'))) {
            // Authentication passed...
            return redirect('other/path');
        }

        $user = \App\Models\User::where([ // This model use your second connection to the other database
            'email' => $request->email,
            'password' => md5($request->password)
        ])->first();

        if ($user) {
            $user->password = bcrypt($request->password);
            $user->save();

            $this->guard()->login($user);

            return redirect('other/path');;
        }

        return redirect('fail-path-with-instructions-for-create-account');

    }
}

我确实建议您在routes/web.php文件中创建一个命名路由以重定向到您的新身份验证 URL,这是因为 laraver 中构建的许多机制会自动将您的用户重定向到正常路由(例如,如果未登录或会话则重定向已到期)。

Route::get('login', 'YourCustomController@login')->name('login');

推荐阅读