Home Backend Development PHP Tutorial Detailed explanation of Auth module examples in Laravel

Detailed explanation of Auth module examples in Laravel

Jan 26, 2018 am 11:14 AM
auth laravel module

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use object-relational mapping (ORM) in PHP to simplify database operations? How to use object-relational mapping (ORM) in PHP to simplify database operations? May 07, 2024 am 08:39 AM

Database operations in PHP are simplified using ORM, which maps objects into relational databases. EloquentORM in Laravel allows you to interact with the database using object-oriented syntax. You can use ORM by defining model classes, using Eloquent methods, or building a blog system in practice.

Comparison of the latest versions of Laravel and CodeIgniter Comparison of the latest versions of Laravel and CodeIgniter Jun 05, 2024 pm 05:29 PM

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

How do the data processing capabilities in Laravel and CodeIgniter compare? How do the data processing capabilities in Laravel and CodeIgniter compare? Jun 01, 2024 pm 01:34 PM

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

Which one is more beginner-friendly, Laravel or CodeIgniter? Which one is more beginner-friendly, Laravel or CodeIgniter? Jun 05, 2024 pm 07:50 PM

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

Laravel vs CodeIgniter: Which framework is better for large projects? Laravel vs CodeIgniter: Which framework is better for large projects? Jun 04, 2024 am 09:09 AM

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

PHP code unit testing and integration testing PHP code unit testing and integration testing May 07, 2024 am 08:00 AM

PHP Unit and Integration Testing Guide Unit Testing: Focus on a single unit of code or function and use PHPUnit to create test case classes for verification. Integration testing: Pay attention to how multiple code units work together, and use PHPUnit's setUp() and tearDown() methods to set up and clean up the test environment. Practical case: Use PHPUnit to perform unit and integration testing in Laravel applications, including creating databases, starting servers, and writing test code.

Laravel vs CodeIgniter: Which framework is better for small projects? Laravel vs CodeIgniter: Which framework is better for small projects? Jun 04, 2024 pm 05:29 PM

For small projects, Laravel is suitable for larger projects that require strong functionality and security. CodeIgniter is suitable for very small projects that require lightweight and ease of use.

See all articles