You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8登录系统实现咨询:默认密码强制修改功能

Laravel 8 实现带默认密码强制修改的登录系统

1. 数据库字段添加

先给用户表新增字段标记是否使用默认密码:

# 创建迁移文件
php artisan make:migration add_is_default_password_to_users_table --table=users

打开生成的迁移文件,添加字段定义:

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->boolean('is_default_password')->default(true);
    });
}

public function down()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('is_default_password');
    });
}

执行迁移:

php artisan migrate

2. 重写登录控制器的认证逻辑

修改app/Http/Controllers/Auth/LoginController.php,重写authenticated方法(该方法在登录验证通过后触发):

use Illuminate\Http\Request;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    protected function authenticated(Request $request, $user)
    {
        // 判断用户是否使用默认密码
        if ($user->is_default_password) {
            // 存入session标记,用于前端触发模态框
            session()->flash('force_change_password', true);
        }
        return redirect()->intended($this->redirectPath());
    }
}

3. 前端模态框实现(Blade模板)

在首页模板(如resources/views/home.blade.php)中添加修改密码模态框,并通过session判断是否自动弹出:

<!-- 若项目已引入Bootstrap可跳过下面两行 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<!-- 修改密码模态框 -->
<div class="modal fade" id="changePasswordModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改默认密码</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{{ route('password.update') }}" method="POST">
                @csrf
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="current_password" class="form-label">当前密码</label>
                        <input type="password" class="form-control" id="current_password" name="current_password" required>
                        @error('current_password')
                            <span class="text-danger">{{ $message }}</span>
                        @enderror
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">新密码</label>
                        <input type="password" class="form-control" id="password" name="password" required>
                        @error('password')
                            <span class="text-danger">{{ $message }}</span>
                        @enderror
                    </div>
                    <div class="mb-3">
                        <label for="password_confirmation" class="form-label">确认新密码</label>
                        <input type="password" class="form-control" id="password_confirmation" name="password_confirmation" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">确认修改</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 自动弹出模态框逻辑 -->
@if(session('force_change_password'))
<script>
    const modal = new bootstrap.Modal(document.getElementById('changePasswordModal'), {
        backdrop: 'static', // 禁止点击背景关闭
        keyboard: false // 禁止ESC关闭
    });
    modal.show();
</script>
@endif

4. 密码修改逻辑处理

首先在routes/web.php添加路由:

use App\Http\Controllers\PasswordController;

Route::post('/password/update', [PasswordController::class, 'update'])->name('password.update')->middleware('auth');

创建app/Http/Controllers/PasswordController.php处理修改请求:

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

class PasswordController extends Controller
{
    public function update(Request $request)
    {
        $request->validate([
            'current_password' => ['required', function ($attribute, $value, $fail) {
                if (!Hash::check($value, auth()->user()->password)) {
                    $fail('当前密码输入错误');
                }
            }],
            'password' => ['required', 'confirmed', 'min:8'],
        ]);

        // 更新密码并标记为非默认状态
        auth()->user()->update([
            'password' => Hash::make($request->password),
            'is_default_password' => false,
        ]);

        session()->forget('force_change_password');
        return redirect()->route('home')->with('success', '密码修改成功');
    }
}

5. 可选:创建用户时设置默认密码

后台创建用户时,设置默认密码并标记状态:

// 示例代码
$user = User::create([
    'name' => '新用户',
    'email' => 'newuser@example.com',
    'password' => Hash::make('123456'), // 默认密码
    'is_default_password' => true,
]);

内容的提问来源于stack exchange,提问作者chemuel castillo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 17:52:43