当前位置:网站首页>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

原网站

版权声明
本文为[Wang Daochang's way of programming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241719271401.html