
# Auth Basics
Laravel cung cấp một hệ thống xác thực mạnh mẽ và dễ sử dụng. Dưới đây là những bước cơ bản để thiết lập và sử dụng hệ thống xác thực trong Laravel.
Bước 1: Cài Đặt Laravel UI
Laravel UI là một package cho phép bạn cài đặt các scaffolding (bộ khung) cho xác thực, bao gồm cả giao diện Bootstrap, Vue, và React.
Đầu tiên, cài đặt Laravel UI:
composer require laravel/ui
Sau đó, bạn có thể tạo scaffolding cho xác thực:
php artisan ui bootstrap --auth
Lệnh này sẽ tạo các route, controller, view cần thiết cho hệ thống xác thực và cài đặt Bootstrap. Nếu bạn muốn sử dụng Vue hoặc React, bạn có thể thay bootstrap
bằng vue
hoặc react
.
Tiếp theo, chạy lệnh để cài đặt các package npm và biên dịch các asset:
npm install
npm run dev
Bước 2: Chạy Migrations
Laravel UI sẽ tạo sẵn các migration cho bảng users. Bạn chỉ cần chạy lệnh migrate để tạo bảng trong database:
php artisan migrate
Bước 3: Routes
Laravel UI sẽ tự động tạo các route cần thiết cho hệ thống xác thực trong file routes/web.php
:
Auth::routes();
Bạn có thể kiểm tra file này để xem các route mà Laravel đã tạo cho bạn, bao gồm login, register, logout, và password reset.
Bước 4: Middleware
Laravel cung cấp middleware để bảo vệ các route của bạn. Middleware này sẽ đảm bảo rằng chỉ có người dùng đã xác thực mới có thể truy cập các route được bảo vệ.
Ví dụ, bạn có thể bảo vệ một route bằng middleware auth
như sau:
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home')->middleware('auth');
Bước 5: Views
Laravel UI sẽ tạo sẵn các view cho các trang login, register, và reset password trong thư mục resources/views/auth
.
# Tips & Tricks about Laravel Auth
1. Login với $user
Khi bạn cần thiết lập một người dùng hiện tại làm người dùng đã xác thực, bạn có thể truyền instance của người dùng đó vào phương thức login
của Facade Auth
. Người dùng này phải là một implementation của interface Illuminate\Contracts\Auth\Authenticatable
. Mô hình App\Models\User
được bao gồm trong Laravel đã triển khai sẵn interface này. Phương pháp này hữu ích khi bạn đã có một instance người dùng hợp lệ, chẳng hạn như ngay sau khi người dùng đăng ký với ứng dụng của bạn.
use Illuminate\Support\Facades\Auth;
$user = User::find(1); // Giả sử bạn đã có instance của người dùng
Auth::login($user);
Ghi Nhớ Đăng Nhập Người Dùng
Auth::login($user, $remember = true);
Sử Dụng Guard
Nếu cần, bạn có thể chỉ định một guard xác thực trước khi gọi phương thức login
:
Auth::guard('admin')->login($user);
Ngoài ra, bạn có thể tham khảo thêm về loginUsingId
2. Lấy id user đã đăng nhập
Auth::user()->id;
// or
Auth::id();
3. Extra Password Confirmation
Laravel cung cấp một tính năng gọi là "Extra Password Confirmation" (Xác nhận mật khẩu bổ sung), yêu cầu người dùng nhập lại mật khẩu của họ để xác nhận danh tính trước khi thực hiện các hành động nhạy cảm như thay đổi email, mật khẩu hoặc xóa tài khoản.
Thiết lập Extra Password Confirmation
Laravel đi kèm với các route và controller cần thiết để quản lý việc xác nhận mật khẩu bổ sung. Bạn có thể sử dụng PasswordConfirmationMiddleware
để bảo vệ các route cần xác nhận mật khẩu bổ sung.
Sử Dụng Middleware
Đầu tiên, bạn cần bảo vệ các route nhạy cảm của mình bằng middleware password.confirm
. Middleware này sẽ kiểm tra xem người dùng đã xác nhận mật khẩu của họ trong một khoảng thời gian nhất định (mặc định là 3 giờ).
Định Nghĩa Route
Trong file routes/web.php
, bạn có thể thêm middleware password.confirm
cho các route nhạy cảm của mình:
Route::get('/settings', [SettingsController::class, 'index'])->name('settings');
Route::get('/settings/security', [SettingsController::class, 'security'])->middleware(['auth', 'password.confirm'])->name('settings.security');
Trong ví dụ trên, route /settings/security
sẽ yêu cầu người dùng xác nhận mật khẩu của họ trước khi truy cập.
Tạo Controller cho Xác Nhận Mật Khẩu
Laravel đã cung cấp sẵn controller và route cho việc xác nhận mật khẩu. Bạn có thể kiểm tra hoặc tùy chỉnh theo nhu cầu.
File: app/Http/Controllers/Auth/ConfirmPasswordController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ConfirmPasswordController extends Controller
{
/**
* Hiển thị form xác nhận mật khẩu.
*
* @return \Illuminate\View\View
*/
public function showConfirmForm()
{
return view('auth.passwords.confirm');
}
/**
* Xác nhận mật khẩu của người dùng.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
public function confirm(Request $request)
{
$request->validate([
'password' => 'required|password',
]);
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended();
}
}
View cho Form Xác Nhận Mật Khẩu
Tạo một file view để hiển thị form xác nhận mật khẩu. Laravel có sẵn file confirm.blade.php
cho form xác nhận mật khẩu trong thư mục resources/views/auth/passwords
.
File: resources/views/auth/passwords/confirm.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Confirm Password') }}</div>
<div class="card-body">
{{ __('Please confirm your password before continuing.') }}
<form method="POST" action="{{ route('password.confirm') }}">
@csrf
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Confirm Password') }}
</button>
@if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
@endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
Route Cho Xác Nhận Mật Khẩu
Laravel đã định nghĩa sẵn route cho xác nhận mật khẩu. Bạn có thể tìm thấy route này trong file routes/web.php
:
Route::get('password/confirm', [ConfirmPasswordController::class, 'showConfirmForm'])->name('password.confirm');
Route::post('password/confirm', [ConfirmPasswordController::class, 'confirm']);
4. Fortify Password Rules
Laravel Fortify cung cấp một cách dễ dàng để tùy chỉnh quy tắc mật khẩu cho ứng dụng của bạn. Bạn có thể định nghĩa các quy tắc mật khẩu tùy chỉnh thông qua lớp Password
.
Thiết Lập Các Quy Tắc Mật Khẩu
Laravel Fortify cung cấp lớp Password
để bạn có thể định nghĩa các quy tắc mật khẩu một cách linh hoạt. Bạn có thể tùy chỉnh các quy tắc này trong phương thức boot
của FortifyServiceProvider
.
Cấu Hình Mặc Định
Trong FortifyServiceProvider
, bạn có thể định nghĩa các quy tắc mật khẩu mặc định như sau:
File: app/Providers/FortifyServiceProvider.php
<?php
namespace App\Providers;
use App\Actions\Fortify\CreateNewUser;
use App\Actions\Fortify\ResetUserPassword;
use App\Actions\Fortify\UpdateUserPassword;
use App\Actions\Fortify\UpdateUserProfileInformation;
use Illuminate\Support\ServiceProvider;
use Laravel\Fortify\Fortify;
use Illuminate\Validation\Rules\Password;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Fortify::createUsersUsing(CreateNewUser::class);
Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
// Cấu hình các quy tắc mật khẩu
Password::defaults(function () {
return Password::min(8)
->mixedCase()
->letters()
->numbers()
->symbols()
->uncompromised();
});
}
}
Trong đoạn mã trên, các quy tắc mật khẩu được thiết lập như sau:
- min(8): Mật khẩu phải có ít nhất 8 ký tự.
- mixedCase(): Mật khẩu phải có cả chữ hoa và chữ thường.
- letters(): Mật khẩu phải có ít nhất một chữ cái.
- numbers(): Mật khẩu phải có ít nhất một chữ số.
- symbols(): Mật khẩu phải có ít nhất một ký tự đặc biệt.
- uncompromised(): Mật khẩu không được nằm trong danh sách các mật khẩu đã bị lộ.
Danh mục
Bài viết liên quan

Hiển thị giá trị trong Blade
Author: | ADMIN |
---|

Cấu Trúc Điều Kiện và Vòng Lặp Trong Blade
Author: | ADMIN |
---|

Layout: @include, @extends, @section, @yield
Author: | ADMIN |
---|

Blade Components
Author: | ADMIN |
---|
Bài viết khác

Blade Basics
Author: | ADMIN |
---|

9 Mẹo Hữu Ích Khi Sử Dụng Blade Trong Laravel
Author: | ADMIN |
---|

Hiển thị giá trị trong Blade
Author: | ADMIN |
---|