Bảo mật là một trong những yếu tố quan trọng khi phát triển ứng dụng web, đặc biệt là bảo mật mật khẩu. Trong Laravel 11, bạn có thể ngăn người dùng nhập mật khẩu yếu bằng cách sử dụng custom rule, authentication scaffoldvalidation rule. Trong bài viết này, codetuthub.com sẽ hướng dẫn bạn chi tiết từng bước để đảm bảo người dùng chỉ nhập mật khẩu đủ mạnh khi đăng ký tài khoản.

1. Cài đặt Laravel 11

Trước tiên, bạn cần cài đặt Laravel 11 bằng Composer. Nếu bạn chưa có Laravel, hãy chạy lệnh sau:

shell
composer create-project --prefer-dist laravel/laravel myapp

Sau khi cài đặt xong, di chuyển vào thư mục dự án:

shell
cd myapp

Tiếp theo, chỉnh sửa thông tin kết nối database ở file .env (nhớ thay đổi giá trị phù hợp với máy chủ Database của bạn):

shell
DB_CONNECTION=mysql
DB_HOST=0.0.0.0
DB_PORT=3306
DB_DATABASE=demo_laravel
DB_USERNAME=db_username
DB_PASSWORD=db_password

Chạy migrations và khởi động ứng dụng bằng các lệnh:

shell
php artisan migrate
php artisan serve

Ứng dụng Laravel của bạn sẽ chạy trên http://127.0.0.1:8000/.

2. Tạo custom rule cho mật khẩu

Laravel cho phép bạn tạo Custom Validation Rule để kiểm tra mức độ mạnh của mật khẩu. Chúng ta sẽ tạo một rule mới để đảm bảo mật khẩu có độ phức tạp nhất định.

Chạy lệnh sau để tạo StrongPassword:

shell
php artisan make:rule StrongPassword

Sau khi tạo xong, mở file app/Rules/StrongPassword.php và chỉnh sửa nội dung như sau:

php
app/Rules/StrongPassword.php
<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class StrongPassword implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/', $value)) {
            $fail('Mật khẩu phải có ít nhất 8 ký tự, bao gồm chữ hoa, chữ thường, số và ký tự đặc biệt.');
        }
    }
}

Quy tắc này yêu cầu mật khẩu:

  • Ít nhất 8 ký tự
  • Có ít nhất một chữ hoa và một chữ thường
  • Có ít nhất một số
  • Có ít nhất một ký tự đặc biệt (@$!%*?&)

(*) Bạn cũng có thể custom validate password để ngăn người dùng nhập các mật khẩu dễ đoán:

php
$commonPasswords = [
            '123123',
            '123456',
            '1111111',
            '1234567890',
            'password',
            'password1',
            'password2',
            // Others ....
        ];

        if (in_array($value, $commonPasswords)) {
            $fail('Mật khẩu đã chọn không đủ mạnh. Hãy thử lại bằng chuỗi an toàn hơn.');
        }

3. Cài đặt authentication scaffold

Laravel cung cấp scaffold để tạo chức năng xác thực nhanh chóng. Bạn có thể cài đặt Laravel Breeze để quản lý hệ thống xác thực:

shell
composer require laravel/breeze --dev

Sau đó, chạy lệnh:

shell
php artisan breeze:install

Chọn Blade hoặc Vue/React, và các cài đặt khác sau đó chạy:

shell
npm install && npm run dev

4. Thêm validation rule vào hệ thống đăng ký

Sau khi thiết lập hệ thống xác thực, bạn cần thêm validation rule vào form đăng ký. Mở file app/Http/Requests/Auth/RegisterRequest.php (hoặc app/Http/Controllers/Auth/RegisterUserController.php nếu không dùng form request) và chỉnh sửa phương thức rules():

php
app/Http/Controllers/Auth/RegisterUserController.php
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Rules\StrongPassword;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(): View
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', new StrongPassword()],
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

        event(new Registered($user));

        Auth::login($user);

        return redirect(route('dashboard', absolute: false));
    }
}

Điều này đảm bảo rằng bất kỳ mật khẩu nào không đủ mạnh sẽ bị từ chối khi đăng ký.

5. Chạy và kiểm tra ứng dụng Laravel

Sau khi đã thêm các quy tắc mật khẩu, khởi động lại ứng dụng:

shell
php artisan serve

Mở trình duyệt và truy cập http://127.0.0.1:8000/register, thử nhập mật khẩu yếu (ví dụ: password123) và bạn sẽ thấy thông báo lỗi.

Nếu nhập một mật khẩu mạnh hơn, ví dụ như Secure@1234, đăng ký sẽ thành công.

6. Kết luận

Bằng cách sử dụng custom validation rule, bạn có thể dễ dàng ngăn chặn người dùng nhập mật khẩu yếu trong ứng dụng Laravel 11. Đây là một bước quan trọng để tăng cường bảo mật, bảo vệ dữ liệu của người dùng trước các cuộc tấn công tiềm ẩn.

Hy vọng hướng dẫn này từ codetuthub.com sẽ giúp bạn bảo mật tốt hơn hệ thống đăng nhập của mình. Nếu có bất kỳ câu hỏi nào, hãy để lại bình luận bên dưới!