dongmeng9048 2016-11-01 04:59
浏览 131
已采纳

更改laravel哈希机制以加密并将密码存储在users表中

As laravel uses its own mechanism to encrypt and save the password in users table. But i want to change the password encryption mechanism and want to write my own, also the two inbuilt function of laravel authentication should work according to my my password encryption mechanism

check() and attempt()

Anyone please tell me how to do that..

  • 写回答

1条回答 默认 最新

  • douqiu1604 2016-11-01 05:26
    关注

    Replacing the laravel authentication with a custom authentication

    I had built my laravel project and then had a task to replace the larevel default authentication with a custom authentication module I could not find any post that could help me fix this issue and had to refer to many articles . There fore i decided to make a post on how this could be done So as to help any one else facing the similar issue.

    1.Files needed to be modified :

    a) config/auth.php :
    Replace your eloquent driver with your custom driver

    return [
    
    
    /*
    |--------------------------------------------------------------------------
    | Default Authentication Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the authentication driver that will be utilized.
    | This driver manages the retrieval and authentication of the users
    | attempting to get access to protected areas of your application.
    |
    | Supported: "database", "eloquent"
    |
    */
    
    // 'driver' => 'eloquent', 
    
    'driver' => 'custom',
    
        /*
    |--------------------------------------------------------------------------
    | Authentication Model
    |--------------------------------------------------------------------------
    |
    | When using the "Eloquent" authentication driver, we need to know which
    | Eloquent model should be used to retrieve your users. Of course, it
    | is often just the "User" model but you may use whatever you like.
    |
    */
    
    'model' => 'App\User',
    
    /*
    |--------------------------------------------------------------------------
    | Authentication Table
    |--------------------------------------------------------------------------
    |
    | When using the "Database" authentication driver, we need to know which
    | table should be used to retrieve your users. We have chosen a basic
    | default value but you may easily change it to any table you like.
    |
    */
    
    'table' => 'user',
    
    /*
    |--------------------------------------------------------------------------
    | Password Reset Settings
    |--------------------------------------------------------------------------
    |
    | Here you may set the options for resetting passwords including the view
    | that is your password reset e-mail. You can also set the name of the
    | table that maintains all of the reset tokens for your application.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */
    
    'password' => [
        'email' => 'emails.password',
        'table' => 'password_resets',
        'expire' => 60,
    ],
    

    ];

    b) config/app.php:
    Add your custom provider to the list of providers 'App\Providers \CustomAuthProvider',

    2.Files needed to be added
    a. providers/CustomAuthProvider.php:
    Create a new Custom Provider that uses the custom driver that was defined earlier

    use App\Auth\CustomUserProvider;
    use Illuminate\Support\ServiceProvider;
    
    class CustomAuthProvider extends ServiceProvider {
    
    
    /**
    * Bootstrap the application services.
    *
    * @return void
    */
    public function boot()
    {
    
        $this->app['auth']->extend('custom',function()
        {
    
            return new CustomUserProvider();
        });
    }
    
    /**
    * Register the application services.
    *
    * @return void
    */
    public function register()
    {
        //
    }
    
    
    }
    

    b. Auth/CutomerUserProvider.php
    This class will replace the eloquentUserProvider and where all house keeping procedrues can be initiated (after login / before logout) .

    namespace App\Auth;
    use App\UserPoa; use Carbon\Carbon; 
    use Illuminate\Auth\GenericUser; 
    use   Illuminate\Contracts\Auth\Authenticatable; 
    use Illuminate\Contracts\Auth\UserProvider;
    
    class CustomUserProvider implements UserProvider {
    
    /**
    * Retrieve a user by their unique identifier.
    *
    * @param  mixed $identifier
    * @return \Illuminate\Contracts\Auth\Authenticatable|null
    */
    public function retrieveById($identifier)
    {
        // TODO: Implement retrieveById() method.
    
    
        $qry = UserPoa::where('admin_id','=',$identifier);
    
        if($qry->count() >0)
        {
            $user = $qry->select('admin_id', 'username', 'first_name', 'last_name', 'email', 'password')->first();
    
            $attributes = array(
                'id' => $user->admin_id,
                'username' => $user->username,
                'password' => $user->password,
                'name' => $user->first_name . ' ' . $user->last_name,
            );
    
            return $user;
        }
        return null;
    }
    
    /**
    * Retrieve a user by by their unique identifier and "remember me" token.
    *
    * @param  mixed $identifier
    * @param  string $token
    * @return \Illuminate\Contracts\Auth\Authenticatable|null
    */
    public function retrieveByToken($identifier, $token)
    {
        // TODO: Implement retrieveByToken() method.
        $qry = UserPoa::where('admin_id','=',$identifier)->where('remember_token','=',$token);
    
        if($qry->count() >0)
        {
            $user = $qry->select('admin_id', 'username', 'first_name', 'last_name', 'email', 'password')->first();
    
            $attributes = array(
                'id' => $user->admin_id,
                'username' => $user->username,
                'password' => $user->password,
                'name' => $user->first_name . ' ' . $user->last_name,
            );
    
            return $user;
        }
        return null;
    
    
    
    }
    
    /**
    * Update the "remember me" token for the given user in storage.
    *
    * @param  \Illuminate\Contracts\Auth\Authenticatable $user
    * @param  string $token
    * @return void
    */
    public function updateRememberToken(Authenticatable $user, $token)
    {
        // TODO: Implement updateRememberToken() method.
        $user->setRememberToken($token);
    
        $user->save();
    
    }
    
    /**
    * Retrieve a user by the given credentials.
    *
    * @param  array $credentials
    * @return \Illuminate\Contracts\Auth\Authenticatable|null
    */
    public function retrieveByCredentials(array $credentials)
    {
        // TODO: Implement retrieveByCredentials() method.
        $qry = UserPoa::where('username','=',$credentials['username']);
    
        if($qry->count() >0)
        {
            $user = $qry->select('admin_id','username','first_name','last_name','email','password')->first();
    
    
    
    
            return $user;
        }
        return null;
    
    
    }
    
    /**
    * Validate a user against the given credentials.
    *
    * @param  \Illuminate\Contracts\Auth\Authenticatable $user
    * @param  array $credentials
    * @return bool
    */
    public function validateCredentials(Authenticatable $user, array $credentials)
    {
        // TODO: Implement validateCredentials() method.
        // we'll assume if a user was retrieved, it's good
    
        if($user->username == $credentials['username'] && $user->getAuthPassword() == md5($credentials['password'].\Config::get('constants.SALT')))
        {
    
            $user->last_login_time = Carbon::now();
            $user->save();
    
            return true;
        }
        return false;
    
    
    }
    
    }
    

    UsePoa (This is my model for the admin table): This is a Model class that i created for my admin table .It implements Illuminate\Contracts\Auth\Authenticatable

    use Illuminate\Auth\Authenticatable; 
    use Illuminate\Database\Eloquent\Model;
    
    use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
    
    class UserPoa extends Model implements AuthenticatableContract {
    
    use Authenticatable;
    protected $table = 'admin';
    protected $primaryKey  = 'admin_id';
    public $timestamps = false;
    
    }
    

    3.Files need to know about Guard.php
    This is the class that will call your User Provider depending on what is defined in the driver. Originally it used to be the EloquentUserProvider .But in this case I have replaced it with the CustomUserProvider. Below is how the methods in the CustomUserProvider are called by the Guard.

    1 . Login :
    A. retrieveByCredentials is called to check if the user exists.
    B.ValidateCredentials is called to verify if the username and password are correct .
    Note: The object that was produced in the retrieveByCredentials is sent to the ValidateCredentials and therefore no second db access is required.

    1. Authenticate a page: Whenever an attempt is made to see if a user has been logged in: retrieveById($identifier) is called.

    Logout with remember me setup the method updateRememberToken(Authenticatable $user, $token) will be called.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题