
在 Laravel Jetstream 项目中,默认使用 Fortify 进行身份验证。为了增强安全性,并仅允许管理员用户登录,我们需要修改默认的登录流程,加入对 is_admin 字段的验证。以下提供了两种实现方式,您可以根据项目需求选择合适的方法。
自定义身份验证逻辑
Jetstream 允许我们自定义身份验证逻辑,通过 Fortify::authenticateUsing 方法,我们可以完全控制用户的登录过程。
方法一:修改 User 模型
-
打开 app/Models/User.php 文件。
-
在 User 模型中添加 boot 方法,并在其中使用 Fortify::authenticateUsing 注册自定义的身份验证逻辑。
<?php
namespace App/Models;
use Illuminate/Contracts/Auth/MustVerifyEmail;
use Illuminate/Database/Eloquent/Factories/HasFactory;
use Illuminate/Foundation/Auth/User as Authenticatable;
use Illuminate/Notifications/Notifiable;
use Laravel/Fortify/Fortify;
use Illuminate/Http/Request;
use Illuminate/Support/Facades/Hash;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'is_admin', // 确保 is_admin 在 fillable 中
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Bootstrap any application services.
*
* @return void
*/
public static function boot()
{
parent::boot();
Fortify::authenticateUsing(function (Request $request) {
$user = User::where(['email' => $request->email, 'is_admin' => 1])->first();
if ($user && Hash::check($request->password, $user->password)) {
return $user;
}
});
}
}
注意事项:
- 确保 is_admin 字段存在于 fillable 数组中,以便可以进行批量赋值。
- boot 方法必须是 static 的。
方法二:修改 FortifyServiceProvider
-
打开 app/Providers/FortifyServiceProvider.php 文件。
-
在 boot 方法中使用 Fortify::authenticateUsing 注册自定义的身份验证逻辑。
<?php
namespace App/Providers;
use App/Models/User;
use Illuminate/Http/Request;
use Illuminate/Support/Facades/Hash;
use Illuminate/Support/ServiceProvider;
use Laravel/Fortify/Fortify;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Fortify::authenticateUsing(function (Request $request) {
$user = User::where(['email' => $request->email, 'is_admin' => 1])->first();
if ($user && Hash::check($request->password, $user->password)) {
return $user;
}
});
}
}
代码解释
以上两种方法的核心代码都是:
Fortify::authenticateUsing(function (Request $request) {
$user = User::where(['email' => $request->email, 'is_admin' => 1])->first();
if ($user && Hash::check($request->password, $user->password)) {
return $user;
}
});
这段代码首先根据请求中的 email 和 is_admin 字段查询用户。如果找到用户,并且密码验证成功,则返回该用户对象,否则返回 null,Fortify 会自动处理登录失败的情况。
安全性考虑
不要使用隐藏字段传递 is_admin 标志。 这样做会带来安全风险,因为用户可以通过修改前端代码来绕过验证。应该始终在后端验证 is_admin 字段。
总结
通过自定义 Fortify 的身份验证逻辑,我们可以轻松地修改 Laravel Jetstream 的登录流程,以满足特定的业务需求。本文介绍了两种实现方法,并强调了安全性问题。根据您的项目结构和个人偏好,选择最适合您的方案。记住,安全性始终是第一位的。
以上就是修改 Laravel Jetstream 登录流程以验证管理员权限的详细内容,更多请关注php中文网其它相关文章!