Detailed explanation of Auth module examples in Laravel

小云云
Release: 2023-03-19 16:50:02
Original
1666 people have browsed it

This article is based on the analysis and writing of the localization module code of Laravel 5.4 version; I hope it can help everyone learn the Auth module better.

Module composition

The Auth module is functionally divided into two parts: user authentication and permission management; in terms of file composition, the Illuminate\Auth\Passwords directory is for password reset or A small module for forgetting password processing. Illuminate\Auth is the module responsible for user authentication and permission management. Illuminate\Foundation\Auth provides a series of specific logic implementations such as login, password modification, and password reset;

Next The figure shows the relationship between the various files of the Auth module and gives a brief description;

User Authentication

HTTP itself is stateless, usually in the system During the interaction process, use the account or Token identification to determine the authenticated user;

Configuration file interpretation

return [
 'defaults' => [
 'guard' => 'web',
 ...
 ],
 'guards' => [ 
 'web' => [
  'driver' => 'session',
  'provider' => 'users',
 ],
 'api' => [ 
  'driver' => 'token', 
  'provider' => 'users',
 ],
 ],
 'providers' => [
 'users' => [
  'driver' => 'eloquent',
  'model' => App\User::class,
 ], 
 ],
], 
];
Copy after login

Understand from bottom to top;

  • Providers is an interface that provides user data, and the driver object and target object must be marked; here, the key name users is the name of a set of providers, driven by eloquent, and modal is App\User::class;

  • The guards part is configured for the authentication management part; there are two authentication methods, one is called web, and the other is api; web authentication is based on Session interaction, and the user ID is obtained based on the sessionId. In the users provider Query out this user; api authentication is based on token value interaction, and also uses the users provider;

  • defaults item shows that web authentication is used by default;

Authentication

Session binding authentication information:

// $credentials数组存放认证条件,比如邮箱或者用户名、密码
// $remember 表示是否要记住,生成 `remember_token`
public function attempt(array $credentials = [], $remember = false) 
 
public function login(AuthenticatableContract $user, $remember = false)
 
public function loginUsingId($id, $remember = false)
Copy after login

HTTP basic authentication, the authentication information is placed in the request header; subsequent requests are accessed through sessionId;

public function basic($field = 'email', $extraConditions = [])
Copy after login

Only authenticates in the current session, and does not record authentication information in the session:

public function once(array $credentials = [])

public function onceUsingId($id)

public function onceBasic($field = 'email', $extraConditions = [])
Copy after login

During the authentication process (including registration, forgotten password), the defined events are as follows:

##AttemptingAttempt to verify eventAuthenticatedVerification passed eventFailedVerification failed eventLockoutThe number of failures exceeds the limit, lock the request to access the event againLogiWhen logging in successfully through 'remember_token' , the event called LogoutUser exit eventRegisteredUser registration event

还有一些其他的认证方法:

  • 检查是否存在认证用户:Auth::check()

  • 获取当前认证用户:Auth::user()

  • 退出系统:Auth::logout()

密码处理

配置解读

return [
 'defaults' => [
  'passwords' => 'users',
  ...
 ],
 
 'passwords' => [
  'users' => [
   'provider' => 'users',
   'table' => 'password_resets',
   'expire' => 60,
  ],
 ],
]
Copy after login

从下往上,看配置;

  • passwords数组是重置密码的配置;users是配置方案的别名,包含三个元素:provider(提供用户的方案,是上面providers数组)、table(存放重置密码token的表)、expire(token过期时间)

  • default 项会设置默认的 passwords 重置方案;

重置密码的调用与实现

先看看Laravel的重置密码功能是怎么实现的:

public function reset(array $credentials, Closure $callback) {
 // 验证用户名、密码和 token 是否有效
 $user = $this->validateReset($credentials);

 if (! $user instanceof CanResetPasswordContract) {
   return $user;
 } 
 
 $password = $credentials['password'];
 // 回调函数执行修改密码,及持久化存储
 $callback($user, $password);
 // 删除重置密码时持久化存储保存的 token
 $this->tokens->delete($user);

 return static::PASSWORD_RESET;
}
Copy after login

再看看Foundation\Auth模块封装的重置密码模块是怎么调用的:

// 暴露的重置密码 API
public function reset(Request $request) {
 // 验证请求参数 token、email、password、password_confirmation
 $this->validate($request, $this->rules(), $this->validationErrorMessages());
 // 调用重置密码的方法,第二个参数是回调,做一些持久化存储工作
 $response = $this->broker()->reset(
  $this->credentials($request), function ($user, $password) {
  $this->resetPassword($user, $password);
  }
 );
 // 封装 Response
 return $response == Password::PASSWORD_RESET
  ? $this->sendResetResponse($response)
  : $this->sendResetFailedResponse($request, $response);
}

// 获取重置密码时的请求参数
protected function credentials(Request $request) {
 return $request->only(
  'email', 'password', 'password_confirmation', 'token'
 );
}

// 重置密码的真实性验证后,进行的持久化工作
protected function resetPassword($user, $password) {
 // 修改后的密码、重新生成 remember_token
 $user->forceFill([
  'password' => bcrypt($password),
  'remember_token' => Str::random(60),
 ])->save();
 // session 中的用户信息也进行重新赋值          
 $this->guard()->login($user);
}
Copy after login

“忘记密码 => 发邮件 => 重置密码” 的大体流程如下:

  • 点击“忘记密码”,通过路由配置,跳到“忘记密码”页面,页面上有“要发送的邮箱”这个字段要填写;

  • 验证“要发送的邮箱”是否是数据库中存在的,如果存在,即向该邮箱发送重置密码邮件;

  • 重置密码邮件中有一个链接(点击后会携带 token 到修改密码页面),同时数据库会保存这个 token 的哈希加密后的值;

  • 填写“邮箱”,“密码”,“确认密码”三个字段后,携带 token 访问重置密码API,首页判断邮箱、密码、确认密码这三个字段,然后验证 token是否有效;如果是,则重置成功;

权限管理

权限管理是依靠内存空间维护的一个数组变量abilities来维护,结构如下:

$abilities = array(
 '定义的动作名,比如以路由的 as 名(common.dashboard.list)' => function($user) {
  // 方法的参数,第一位是 $user, 当前 user, 后面的参数可以自行决定
  return true; // 返回 true 意味有权限, false 意味没有权限
 },
 ......
);
Copy after login

但只用 $abilities,会使用定义的那部分代码集中在一起太烦索,所以有policy策略类的出现;

policy策略类定义一组实体及实体权限类的对应关系,比如以文章举例:

有一个 Modal实体类叫 Post,可以为这个实体类定义一个PostPolicy权限类,在这个权限类定义一些动作为方法名;

class PostPolicy {
 // update 权限,文章作者才可以修改
 public function update(User $user, Post $post) {
  return $user->id === $post->user_id;
 }
}
Copy after login

然后在ServiceProvider中注册,这样系统就知道,如果你要检查的类是Post对象,加上你给的动作名,系统会找到PostPolicy类的对应方法;

protected $policies = [
 Post::class => PostPolicy::class,
];
Copy after login

怎么调用呢?

对于定义在abilities数组的权限:

  • 当前用户是否具备common.dashboard.list权限:Gate::allows('common.dashboard.list')

  • 当前用户是否具备common.dashboard.list权限:! Gate::denies('common.dashboard.list')

  • 当前用户是否具备common.dashboard.list权限:$request->user()->can('common.dashboard.list')

  • 当前用户是否具备common.dashboard.list权限:! $request->user()->cannot('common.dashboard.list')

  • 指定用户是否具备common.dashboard.list权限:Gate::forUser($user)->allows('common.dashboard.list')

对于policy策略类调用的权限:

  • 当前用户是否可以修改文章(Gate 调用):Gate::allows('update', $post)

  • 当前用户是否可以修改文章(user 调用):$user->can('update', $post)

  • 当前用户是否可以修改文章(用帮助函数):policy($post)->update($user, $post)

  • 当前用户是否可以修改文章(Controller 类方法中调用):$this->authorize('update', $post);

  • 当前用户是否可以修改文章(Controller 类同名方法中调用):$this->authorize($post);

  • 指定用户是否可以修改文章(Controller 类方法中调用):$this->authorizeForUser($user, 'update', $post);

有用的技巧

获取当前系统注册的权限,包括两部分abilities和policies数组内容,代码如下:

$gate = app(\Illuminate\Contracts\Auth\Access\Gate::class);
$reflection_gate = new ReflectionClass($gate);

$policies = $reflection_gate->getProperty('policies');
$policies->setAccessible(true);
// 获取当前注册的 policies 数组
dump($policies->getValue($gate));
                          
$abilities = $reflection_gate->getProperty('abilities');          
$abilities->setAccessible(true);
// 获取当前注册的 abilities 数组
dump($abilities->getValue($gate));
Copy after login

相关推荐:

Laravel5.3如何通过公共的auth模块验证不同表中的用户

Event name Description

The above is the detailed content of Detailed explanation of Auth module examples in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template