当前位置:网站首页>Laravel authentication module auth
Laravel authentication module auth
2022-06-24 23:12:00 【Wang Daochang's way of programming】
One 、 To configure
config/auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',// Point to llluminate/Auth/SessionGuard.php
'provider' => 'users',
],
'api' => [
'driver' => 'token', // Point to llluminate/Auth/TokenGuard.php
'provider' => 'wx_user',
'hash' => false,//TokenGuard.php File class properties
'input' => 'token', //TokenGuard.php File class properties
'storage_key' => 'token', //TokenGuard.php File class properties
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'wx_user' => [
'driver' => 'eloquent',
'model' =>App\Model\UserModel::class,
]
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
Two 、 Based on using
Auth::check() // Judge whether the user logs in ,false Redirect /login, Why Redirect::guest() without Redirect::to()? because guest() When redirecting, the current url Save to session in , After logging in, use Redirect::intended() Method to jump to the previous page .
Auth::attempt(array('email' => $email, 'password' => $password)) //attempt Receive an array as a parameter 1, The value of this parameter will be used to find the user data in the database . If used email Value in the database , If found, it will password The value hash is encrypted and matches the password in the database , If it matches , Create an authenticated session to the user . When user identity authentication is successful attempt Method will return true, Otherwise, return false.
//Auth Only help implement validation logic , If successful, it will write session, The next time Auth::check() It passed when .
//Redirect::intended(‘/’) Jump to the previous page , Such as Redirect::guest() Method , that intended Will jump to that time url, And its parameter is just a default value , No more history url I'll jump to ’/’.
//Auth There are other ways , Such as Auth::basic() Can be realized http basic authentication .
3、 ... and 、 Custom encryption verification
3.1 seek auth modular
# config/app.php
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
call Auth It's actually called Illuminate\Support\Facades\Auth::class
, Open file
class Auth extends Facade{
protected static function getFacadeAccessor(){
return 'auth';
}
}
Auth It's through Facade Dynamically bound , Bound to the vendor/laravel/framework/src/Illuminate/AuthServiceProvider
in
class AuthServiceProvider extends ServiceProvider{
protected function registerAuthenticator(){
$this->app->singleton('auth', function ($app) {
$app['auth.loaded'] = true;
return new AuthManager($app);
});
$this->app->singleton('auth.driver', function ($app) {
return $app['auth']->guard();
});
}
}
Default Auth
The binding AuthManager
, open AuthManager
file
<?php
namespace Illuminate\Auth;
use Closure;
use InvalidArgumentException;
use Illuminate\Contracts\Auth\Factory as FactoryContract;
class AuthManager implements FactoryContract{
use CreatesUserProviders;
protected $app;
protected $guards = [];
public function guard($name = null){
$name = $name ?: $this->getDefaultDriver();
return $this->guards[$name]??$this->guards[$name] = $this->resolve($name);
}
public function getDefaultDriver(){
return $this->app['config']['auth.defaults.guard'];
}
public function __call($method, $parameters){
return $this->guard()->{
$method}(...$parameters);
}
}
Did not find attempt Method , But there are __call
Magic methods , Direct use dd(get_class($this->guard()));
real attempt By whom ? Print SessionGuard, open Illuminate\Auth\SessionGuard, Finally found attempt Realization
class SessionGuard implements StatefulGuard, SupportsBasicAuth
{
use GuardHelpers, Macroable;
public function attempt(array $credentials = [], $remember = false){
$this->fireAttemptEvent($credentials, $remember);
$this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
if ($this->hasValidCredentials($user, $credentials)) {
$this->login($user, $remember);
return true;
}
$this->fireFailedEvent($user, $credentials);
return false;
}
This is a attempt
Realization , adopt $this->provider->retrieveByCredentials($credentials)
Get user information , And verify , If successful, log in , And back to true, So the password verification we really do must be retrieveByCredentials
In this method Laravel By default UserProvider
by EloquentUserProvider
Open the change method
class EloquentUserProvider implements UserProvider{
protected $hasher;
protected $model;
public function __construct(HasherContract $hasher, $model){
$this->model = $model;
$this->hasher = $hasher;
}
public function validateCredentials(UserContract $user, array $credentials){
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
public function setHasher(HasherContract $hasher){
$this->hasher = $hasher;
return $this;
}
}
So here hasher It is the default of the system BcryptHasher 了 , Modify him and inject your own haser.ok, Start doing it
3.2 Write your own password rules hasher
<?php
namespace App\Helpers\Hasher;
use Illuminate\Contracts\Hashing\Hasher;
class MD5Hasher implements Hasher{
public function check($value, $hashedValue, array $options = []){
return $this->make($value) === $hashedValue;
}
public function needsRehash($hashedValue, array $options = []){
return false;
}
public function make($value, array $options = []){
$value = env('SALT', '').$value;
return md5($value); // Write your own encryption method here
}
}
3.3 Using one's own Hasher Replace the default Hasher
establish MD5HashServiceProvider
php artisan make:provider MD5HashServiceProvider
Add the following method
<?php
namespace App\Providers;
use App\Helpers\Hasher\MD5Hasher;
use Illuminate\Support\ServiceProvider;
class MD5HashServiceProvider extends ServiceProvider{
public function boot(){
$this->app->singleton('hash', function () {
return new MD5Hasher;
});
}
public function register(){
}
public function provides(){
return ['hash'];
}
}
And then in config/app.php
Of providers
in , take Illuminate\Hashing\HashServiceProvider::class,
Replace with \App\Providers\MD5HashServiceProvider::class,
OK, Be accomplished
Four 、 Customize auth verification
4.1 modify user model
# newly added , Get the fields to be verified
public function getAuthPassword (){
return [
'password'=> $this->attributes['password'],
'salt'=> $this->attributes['code']
];
}
4.2 newly added provider
php artisan make:provider UserServiceProvider
# rewrite EloquentUserProvider Class validateCredentials Method
class MyUserProvider extends EloquentUserProvider{
public function __construct (HasherContract $hasher, $model){
$this->model = $model;
$this->hasher = $hasher;
}
public function register(){
}
public function boot(){
}
// Authenticate whether a given user and a given credential match
public function validateCredentials (Authenticatable $user, array $credentials){
$plain = $credentials['password'];
$secret = $user->getAuthPassword();
if(password_verify($plain, $secret)){
return true;
} elseif($this->think_ucenter_md5($plain) === $secret){
$user->password = password_hash($plain, PASSWORD_DEFAULT);
$user->save();
return true;
}
}
public function think_ucenter_md5 ($str){
return md5(sha1($str) . 'VvKl0QZBE7nao5xtXqGkWrMPchRbHdwmLF361izT');
}
}
4.3 stay AppServiceProvider Of boot register
Auth::provider('myuserprovider', function(){
return new MyUserProvider(); // Returns a custom user provider
});
4.4 modify config/auth.php
stay config\auth.php
Of guards Add custom... To the array guard, A custom guard It consists of two parts : driver and provider.
'oustn' => [
'driver' => 'myguard',
'provider' => 'myusers',
],
...
// stay providers Add custom... To the array user provider
'myusers' => [
'driver' => 'myuserprovider' // Specific fields are created according to user provider Information added , adopt Auth::createUserProvider('myuserprovider') establish
],
5、 ... and 、auth Common functions
<?php
Auth::guard("api")->user();// Get the current authenticated user
Auth::guard("api")->check();// Determine whether the current user is logged in
Auth::guard("api")->guest();// Judge whether the current user is a tourist ( Not logged in )
Auth::guard("api")->validate();// Authenticate the user according to the message provided
Auth::guard("api")->setUser();// Set the current user
Auth::guard("api")->attempt();// Verify whether the user is legal according to the provided credentials
Auth::guard("api")->id();
6、 ... and 、 appendix
Explain how to modify Laravel Auth Use salt and password To authenticate users
边栏推荐
- Selection (028) - what is the output of the following code?
- Écoutez le fichier markdown et mettez à jour Hot next. Page JS
- 推送Markdown格式信息到钉钉机器人
- Financial management [4]
- Some updates about a hand slider (6-18, JS reverse)
- gocolly-手册
- laravel学习笔记
- docker安装mysql-简单无坑
- Research Report on market supply and demand and strategy of ceiling power supply device industry in China
- How should we measure agile R & D projects?
猜你喜欢
07_SpingBoot 实现 RESTful 风格
EPICS记录参考2--EPICS过程数据库概念
2022年高处安装、维护、拆除考试模拟100题及模拟考试
Simulated 100 questions and online simulated examination of high voltage electrician examination in 2022
研究生宿舍大盘点!令人羡慕的研究生宿舍来了!
How should we measure agile R & D projects?
canvas 实现图片新增水印
Cases of addition, deletion, modification and search of C # learning for two years and C # import and export (de duplication)
Dig deep into MySQL - resolve the clustered index / secondary index / federated index of InnoDB storage engine
「ARM 架构」是一种怎样的处理器架构?
随机推荐
MySQL kills 10 people. How many questions can you hold on to?
Docker installation MySQL simple without pit
Vulnhub Vegeta: 1
Uncover the secrets of Huawei cloud enterprise redis issue 16: acid'true' transactions beyond open source redis
Financial management [5]
Research and investment strategy report on China's building steel structure anticorrosive coating industry (2022 Edition)
canvas 实现图片新增水印
Listen to the markdown file and hot update next JS page
23研考生注意啦!备考期间最容易中招的骗局,居然是它们?!
「ARM 架构」是一种怎样的处理器架构?
Dig deep into MySQL - resolve the non clustered index of MyISAM storage engine
监听 Markdown 文件并热更新 Next.js 页面
Building Survey [3]
记录一下MySql update会锁定哪些范围的数据
A big factory interview must ask: how to solve the problem of TCP reliable transmission? 8 pictures for you to learn in detail
New, Huawei cloud Kaitian apaas
2022 safety officer-b certificate examination question bank and answers
Research Report on terahertz imaging system industry - market status analysis and development prospect forecast
倍加福(P+F)R2000修改雷达IP
动态菜单,自动对齐