iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 29
0
Software Development

新手後端工程師的學習歷程系列 第 29

Day 29 - Laravel Authentication - Hasher 篇

tags: 2019鐵人賽 Laravel Authentication Hasher

前言

因為我本身對 Authentication 已經有初步瞭解,所以我這邊不講使用方法,而是要講一些細節。今天要跟大家聊聊怎麼更改 Laravel 中 Hasher 的加密方式,由於會追點 source code,建議要看這篇的人,可能要有一點點基礎才行。

Auth::attempt() 中修改加密模式

我們來試看看把 bcrypt 加密模式改為 MD5 加密模式

開始之前

在開始之前,要先搞懂 Auth::attempt() 是怎麼運作的 參考資料

我簡單抓個重點,

  1. Auth::attempt() 是在 SessionGuard.php 中時作出來的
  2. Auth::attempt() 是在 EloquentUserProvider 中會生成一個 HasherContract $hasher)
    • 這個 $hasher 則用來生成加密的密碼驗證密碼
    • HasherContract 則是調用了 use Illuminate\Contracts\Hashing\Hasher as HasherContract;
    • 根據 config\hashing.php 的設定下得知初始設定下的 Hasher 為 BcryptHasher
return [
/*
|--------------------------------------------------------------------------
| Default Hash Driver
|--------------------------------------------------------------------------
|
| This option controls the default hash driver that will be used to hash
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon", "argon2id"
|
*/
'driver' => 'bcrypt',
];

開始實作

其實上面的參考資料已經寫得很完整了,只是我用的是 Laravel 5.7,在實作上面出現了點問題,在這裡把解決方法補上

問題如下

會出現這個問題是因為,Hasher 這個 Contracts 一定要要實作以下四種方法 infomakecheckneedsRehash

<?php

namespace Illuminate\Contracts\Hashing;

interface Hasher
{
    public function info($hashedValue);

    public function make($value, array $options = []);

    public function check($value, $hashedValue, array $options = []);

    public function needsRehash($hashedValue, array $options = []);
}

因此我們只要把 info 的方法補上就可以了(內容是直接複製 BcryptHasher 的做法)

public function info($hashedValue)
{
	return $this->driver()->info($hashedValue);
}

上一篇
Day 28 - Laravel Database 篇 part III
下一篇
Day 30 - Laravel Authentication - error response 篇
系列文
新手後端工程師的學習歷程30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言