認(rèn)證

2018-02-24 15:52 更新

認(rèn)證可以用與緩存和 session 功能相同的方法擴展。再一次的,使用我們已經(jīng)熟悉的 extend 方法:

Auth::extend('riak', function($app)
{
    // 返回 Illuminate\Contracts\Auth\UserProvider 的實現(xiàn)
});

UserProvider 實現(xiàn)只負(fù)責(zé)從永久存儲系統(tǒng)抓取 Illuminate\Contracts\Auth\Authenticatable 實現(xiàn),存儲系統(tǒng)例如: MySQL 、 Riak ,等等。這兩個接口讓 Laravel 認(rèn)證機制無論用戶數(shù)據(jù)如何保存或用什么種類的類來代表它都能繼續(xù)運作。

讓我們來看一下 UserProvider contract :

interface UserProvider {

    public function retrieveById($identifier);
    public function retrieveByToken($identifier, $token);
    public function updateRememberToken(Authenticatable $user, $token);
    public function retrieveByCredentials(array $credentials);
    public function validateCredentials(Authenticatable $user, array $credentials);

}

retrieveById 函數(shù)通常接收一個代表用戶的數(shù)字鍵,例如:MySQL 數(shù)據(jù)庫的自動遞增 ID。這方法應(yīng)該取得符合 ID 的 Authenticatable 實現(xiàn)并返回。

retrieveByToken 函數(shù)用用戶唯一的 $identifier 和保存在 remember_token 字段的「記住我」 $token 來取得用戶。跟前面的方法一樣,應(yīng)該返回 Authenticatable 的實現(xiàn)。

updateRememberToken 方法用新的 $token 更新 $user 的 remember_token 字段。新 token 可以是在「記住我」成功地登錄時,傳入一個新的 token,或當(dāng)用戶注銷時傳入一個 null。

retrieveByCredentials 方法接收當(dāng)嘗試登錄應(yīng)用程序時,傳遞到 Auth::attempt 方法的憑證數(shù)組。這個方法應(yīng)該接著「查找」底層使用的永久存儲,找到符合憑證的用戶。這個方法通常會對 $credentials['username'] 用「 where 」條件查找。 并且應(yīng)該返回一個 UserInterface 接口的實現(xiàn)。這個方法不應(yīng)該嘗試做任何密碼驗證或認(rèn)證。

validateCredentials 方法應(yīng)該通過比較給定的 $user 與 $credentials 來驗證用戶。舉例來說,這個方法可以比較 $user->getAuthPassword() 字串跟 Hash::make 后的 $credentials['password']。這個方法應(yīng)該只驗證用戶的憑證數(shù)組并且返回布爾值。

現(xiàn)在我們已經(jīng)看過 UserProvider 的每個方法,接著來看一下 Authenticatable。記住,提供者應(yīng)該從 retrieveById 和 retrieveByCredentials 方法返回這個接口的實現(xiàn):

interface Authenticatable {

    public function getAuthIdentifier();
    public function getAuthPassword();
    public function getRememberToken();
    public function setRememberToken($value);
    public function getRememberTokenName();

}

這個接口很簡單。 The getAuthIdentifier 方法應(yīng)該返回用戶的「主鍵」。在 MySQL 后臺,同樣,這將會是個自動遞增的主鍵。getAuthPassword 應(yīng)該返回用戶哈希過的密碼。這個接口讓認(rèn)證系統(tǒng)可以與任何用戶類一起運作,無論你使用什么 ORM 或保存抽象層。默認(rèn),Laravel 包含一個實現(xiàn)這個接口的 User 類在 app 文件夾里,所以你可以參考這個類當(dāng)作實現(xiàn)的例子。

最后,當(dāng)我們已經(jīng)實現(xiàn)了 UserProvider,我們準(zhǔn)備好用 Auth facade 來注冊擴展:

Auth::extend('riak', function($app)
{
    return new RiakUserProvider($app['riak.connection']);
});

用 extend 方法注冊驅(qū)動之后,在你的 config/auth.php 配置文件切換到新驅(qū)動。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號