基於 laravel 預設的 auth
實現 api 認證
現在微服務越來越流行了. 很多東西都拆分成獨立的系統,各個系統之間沒有直接的關係. 這樣我們如果做使用者認證肯定是統一的做一個獨立的 使用者認證
系統,而不是每個業務系統都要重新去寫一遍使用者認證相關的東西. 但是又遇到一個問題了. laravel
預設的auth 認證
是基於資料庫做的,如果要微服務架構可怎麼做呢?
實現程式碼如下:
UserProvider 介面:
// 通過唯一標示符獲取認證模型
public function retrieveById($identifier);
// 通過唯一標示符和 remember token 獲取模型
public function retrieveByToken($identifier, $token);
// 通過給定的認證模型更新 remember token
public function updateRememberToken(Authenticatable $user, $token);
// 通過給定的憑證獲取使用者,比如 email 或使用者名稱等等
public function retrieveByCredentials(array $credentials);
// 認證給定的使用者和給定的憑證是否符合
public function validateCredentials(Authenticatable $user, array $credentials);
複製程式碼
Laravel
中預設有兩個 user provider : DatabaseUserProvider
& EloquentUserProvider
.
DatabaseUserProvider
IlluminateAuthDatabaseUserProvider
直接通過資料庫表來獲取認證模型.
EloquentUserProvider
IlluminateAuthEloquentUserProvider
通過 eloquent 模型來獲取認證模型
根據上面的知識,可以知道要自定義一個認證很簡單。
自定義 Provider
建立一個自定義的認證模型,實現 Authenticatable 介面;
AppAuthUserProvider.php
<?php
namespace AppAuth;
use AppModelsUser;
use IlluminateContractsAuthAuthenticatable;
use IlluminateContractsAuthUserProvider as Provider;
class UserProvider implements Provider
{
/**
* Retrieve a user by their unique identifier.
* @param mixed $identifier
* @return IlluminateContractsAuthAuthenticatable|null
*/
public function retrieveById($identifier)
{
return app(User::class)::getUserByGuId($identifier);
}
/**
* Retrieve a user by their unique identifier and "remember me" token.
* @param mixed $identifier
* @param string $token
* @return IlluminateContractsAuthAuthenticatable|null
*/
public function retrieveByToken($identifier, $token)
{
return null;
}
/**
* Update the "remember me" token for the given user in storage.
* @param IlluminateContractsAuthAuthenticatable $user
* @param string $token
* @return bool
*/
public function updateRememberToken(Authenticatable $user, $token)
{
return true;
}
/**
* Retrieve a user by the given credentials.
* @param array $credentials
* @return IlluminateContractsAuthAuthenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
if ( !isset($credentials[`api_token`])) {
return null;
}
return app(User::class)::getUserByToken($credentials[`api_token`]);
}
/**
* Rules a user against the given credentials.
* @param IlluminateContractsAuthAuthenticatable $user
* @param array $credentials
* @return bool
*/
public function validateCredentials(Authenticatable $user, array $credentials)
{
if ( !isset($credentials[`api_token`])) {
return false;
}
return true;
}
}
複製程式碼
Authenticatable 介面:
IlluminateContractsAuthAuthenticatable
Authenticatable 定義了一個可以被用來認證的模型或類需要實現的介面,也就是說,如果需要用一個自定義的類來做認證,需要實現這個介面定義的方法。
<?php
.
.
.
// 獲取唯一標識的,可以用來認證的欄位名,比如 id,uuid
public function getAuthIdentifierName();
// 獲取該標示符對應的值
public function getAuthIdentifier();
// 獲取認證的密碼
public function getAuthPassword();
// 獲取remember token
public function getRememberToken();
// 設定 remember token
public function setRememberToken($value);
// 獲取 remember token 對應的欄位名,比如預設的 `remember_token`
public function getRememberTokenName();
.
.
.
複製程式碼
Laravel 中定義的 Authenticatable trait
,也是 Laravel auth 預設的 User
模型使用的 trait,這個 trait 定義了 User
模型預設認證標示符為 `id`,密碼欄位為password
,remember token
對應的欄位為 remember_token
等等。
通過重寫 User
模型的這些方法可以修改一些設定。
實現自定義認證模型
AppModelsUser.php
<?php
namespace AppModels;
use AppExceptionsRestApiException;
use AppModelsAbstractsRestApiModel;
use IlluminateContractsAuthAuthenticatable;
class User extends RestApiModel implements Authenticatable
{
protected $primaryKey = `guid`;
public $incrementing = false;
protected $keyType = `string`;
/**
* 獲取唯一標識的,可以用來認證的欄位名,比如 id,guid
* @return string
*/
public function getAuthIdentifierName()
{
return $this->primaryKey;
}
/**
* 獲取主鍵的值
* @return mixed
*/
public function getAuthIdentifier()
{
$id = $this->{$this->getAuthIdentifierName()};
return $id;
}
public function getAuthPassword()
{
return ``;
}
public function getRememberToken()
{
return ``;
}
public function setRememberToken($value)
{
return true;
}
public function getRememberTokenName()
{
return ``;
}
protected static function getBaseUri()
{
return config(`api-host.user`);
}
public static $apiMap = [
`getUserByToken` => [`method` => `GET`, `path` => `login/user/token`],
`getUserByGuId` => [`method` => `GET`, `path` => `user/guid/:guid`],
];
/**
* 獲取使用者資訊 (by guid)
* @param string $guid
* @return User|null
*/
public static function getUserByGuId(string $guid)
{
try {
$response = self::getItem(`getUserByGuId`, [
`:guid` => $guid
]);
} catch (RestApiException $e) {
return null;
}
return $response;
}
/**
* 獲取使用者資訊 (by token)
* @param string $token
* @return User|null
*/
public static function getUserByToken(string $token)
{
try {
$response = self::getItem(`getUserByToken`, [
`Authorization` => $token
]);
} catch (RestApiException $e) {
return null;
}
return $response;
}
}
複製程式碼
上面 RestApiModel
是我們公司對 Guzzle
的封裝,用於 php 專案各個系統之間 api
呼叫. 程式碼就不方便透漏了.
Guard 介面
IlluminateContractsAuthGuard
Guard
介面定義了某個實現了 Authenticatable
(可認證的) 模型或類的認證方法以及一些常用的介面。
// 判斷當前使用者是否登入
public function check();
// 判斷當前使用者是否是遊客(未登入)
public function guest();
// 獲取當前認證的使用者
public function user();
// 獲取當前認證使用者的 id,嚴格來說不一定是 id,應該是上個模型中定義的唯一的欄位名
public function id();
// 根據提供的訊息認證使用者
public function validate(array $credentials = []);
// 設定當前使用者
public function setUser(Authenticatable $user);
複製程式碼
StatefulGuard 介面
IlluminateContractsAuthStatefulGuard
StatefulGuard
介面繼承自 Guard
介面,除了 Guard
裡面定義的一些基本介面外,還增加了更進一步、有狀態的 Guard
.
新新增的介面有這些:
// 嘗試根據提供的憑證驗證使用者是否合法
public function attempt(array $credentials = [], $remember = false);
// 一次性登入,不記錄session or cookie
public function once(array $credentials = []);
// 登入使用者,通常在驗證成功後記錄 session 和 cookie
public function login(Authenticatable $user, $remember = false);
// 使用使用者 id 登入
public function loginUsingId($id, $remember = false);
// 使用使用者 ID 登入,但是不記錄 session 和 cookie
public function onceUsingId($id);
// 通過 cookie 中的 remember token 自動登入
public function viaRemember();
// 登出
public function logout();
複製程式碼
Laravel
中預設提供了 3 中 guard :RequestGuard
,TokenGuard
,SessionGuard
.
RequestGuard
IlluminateAuthRequestGuard
RequestGuard 是一個非常簡單的 guard. RequestGuard 是通過傳入一個閉包來認證的。可以通過呼叫 Auth::viaRequest
新增一個自定義的 RequestGuard.
SessionGuard
IlluminateAuthSessionGuard
SessionGuard 是 Laravel web 認證預設的 guard.
TokenGuard
IlluminateAuthTokenGuard
TokenGuard 適用於無狀態 api 認證,通過 token 認證.
實現自定義 Guard
AppAuthUserGuard.php
<?php
namespace AppAuth;
use IlluminateHttpRequest;
use IlluminateAuthGuardHelpers;
use IlluminateContractsAuthGuard;
use IlluminateContractsAuthUserProvider;
class UserGuard implements Guard
{
use GuardHelpers;
protected $user = null;
protected $request;
protected $provider;
/**
* The name of the query string item from the request containing the API token.
*
* @var string
*/
protected $inputKey;
/**
* The name of the token "column" in persistent storage.
*
* @var string
*/
protected $storageKey;
/**
* The user we last attempted to retrieve
* @var
*/
protected $lastAttempted;
/**
* UserGuard constructor.
* @param UserProvider $provider
* @param Request $request
* @return void
*/
public function __construct(UserProvider $provider, Request $request = null)
{
$this->request = $request;
$this->provider = $provider;
$this->inputKey = `Authorization`;
$this->storageKey = `api_token`;
}
/**
* Get the currently authenticated user.
* @return IlluminateContractsAuthAuthenticatable|null
*/
public function user()
{
if(!is_null($this->user)) {
return $this->user;
}
$user = null;
$token = $this->getTokenForRequest();
if(!empty($token)) {
$user = $this->provider->retrieveByCredentials(
[$this->storageKey => $token]
);
}
return $this->user = $user;
}
/**
* Rules a user`s credentials.
* @param array $credentials
* @return bool
*/
public function validate(array $credentials = [])
{
if (empty($credentials[$this->inputKey])) {
return false;
}
$credentials = [$this->storageKey => $credentials[$this->inputKey]];
$this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
return $this->hasValidCredentials($user, $credentials);
}
/**
* Determine if the user matches the credentials.
* @param mixed $user
* @param array $credentials
* @return bool
*/
protected function hasValidCredentials($user, $credentials)
{
return !is_null($user) && $this->provider->validateCredentials($user, $credentials);
}
/**
* Get the token for the current request.
* @return string
*/
public function getTokenForRequest()
{
$token = $this->request->header($this->inputKey);
return $token;
}
/**
* Set the current request instance.
*
* @param IlluminateHttpRequest $request
* @return $this
*/
public function setRequest(Request $request)
{
$this->request = $request;
return $this;
}
}
複製程式碼
在 AppServiceProvider 的 boot 方法新增如下程式碼:
AppProvidersAuthServiceProvider.php
<?php
.
.
.
// auth:api -> token provider.
Auth::provider(`token`, function() {
return app(UserProvider::class);
});
// auth:api -> token guard.
// @throw Exception
Auth::extend(`token`, function($app, $name, array $config) {
if($name === `api`) {
return app()->make(UserGuard::class, [
`provider` => Auth::createUserProvider($config[`provider`]),
`request` => $app->request,
]);
}
throw new Exception(`This guard only serves "auth:api".`);
});
.
.
.
複製程式碼
-
在
configauth.php
的 guards 陣列中新增自定義guard
,一個自定義 guard 包括兩部分:driver
和provider
. -
設定
configauth.php
的 defaults.guard 為api
.
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they`re a perfect start for most applications.
|
*/
`defaults` => [
`guard` => `api`,
`passwords` => `users`,
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user`s data.
|
| Supported: "session", "token"
|
*/
`guards` => [
`web` => [
`driver` => `session`,
`provider` => `users`,
],
`api` => [
`driver` => `token`,
`provider` => `token`,
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user`s data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
`providers` => [
`users` => [
`driver` => `eloquent`,
`model` => AppModelsUser::class,
],
`token` => [
`driver` => `token`,
`model` => AppModelsUser::class,
],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| 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.
|
*/
`passwords` => [
`users` => [
`provider` => `users`,
`table` => `password_resets`,
`expire` => 60,
],
],
];
複製程式碼
使用 方式:
第一次寫這麼多字的文章,寫的不好請多多包涵!!