auth
實現 api 認證如今微服務愈來愈流行了. 不少東西都拆分紅獨立的系統,各個系統之間沒有直接的關係. 這樣咱們若是作用戶認證確定是統一的作一個獨立的 用戶認證
系統,而不是每一個業務系統都要從新去寫一遍用戶認證相關的東西. 可是又遇到一個問題了. laravel
默認的auth 認證
是基於數據庫作的,若是要微服務架構可怎麼作呢?php
// 經過惟一標示符獲取認證模型
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 Illuminate\Auth\DatabaseUserProvider
laravel
直接經過數據庫表來獲取認證模型.web
EloquentUserProvider Illuminate\Auth\EloquentUserProvider
數據庫
經過 eloquent 模型來獲取認證模型api
根據上面的知識,能夠知道要自定義一個認證很簡單。數組
Provider
建立一個自定義的認證模型,實現 Authenticatable 接口;bash
App\Auth\UserProvider.php
cookie
<?php
namespace App\Auth;
use App\Models\User;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider as Provider;
class UserProvider implements Provider {
/** * Retrieve a user by their unique identifier. * @param mixed $identifier * @return \Illuminate\Contracts\Auth\Authenticatable|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 \Illuminate\Contracts\Auth\Authenticatable|null */
public function retrieveByToken($identifier, $token) {
return null;
}
/** * Update the "remember me" token for the given user in storage. * @param \Illuminate\Contracts\Auth\Authenticatable $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 \Illuminate\Contracts\Auth\Authenticatable|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 \Illuminate\Contracts\Auth\Authenticatable $user * @param array $credentials * @return bool */
public function validateCredentials(Authenticatable $user, array $credentials) {
if ( !isset($credentials['api_token'])) {
return false;
}
return true;
}
}
複製代碼
Illuminate\Contracts\Auth\Authenticatable
Authenticatable 定義了一個能夠被用來認證的模型或類須要實現的接口,也就是說,若是須要用一個自定義的類來作認證,須要實現這個接口定義的方法。session
<?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
模型的這些方法能夠修改一些設置。閉包
App\Models\User.php
<?php
namespace App\Models;
use App\Exceptions\RestApiException;
use App\Models\Abstracts\RestApiModel;
use Illuminate\Contracts\Auth\Authenticatable;
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
調用. 代碼就不方便透漏了.
Illuminate\Contracts\Auth\Guard
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);
複製代碼
Illuminate\Contracts\Auth\StatefulGuard
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
.
Illuminate\Auth\RequestGuard
RequestGuard 是一個很是簡單的 guard. RequestGuard 是經過傳入一個閉包來認證的。能夠經過調用 Auth::viaRequest
添加一個自定義的 RequestGuard.
Illuminate\Auth\SessionGuard
SessionGuard 是 Laravel web 認證默認的 guard.
Illuminate\Auth\TokenGuard
TokenGuard 適用於無狀態 api 認證,經過 token 認證.
Guard
App\Auth\UserGuard.php
<?php
namespace App\Auth;
use Illuminate\Http\Request;
use Illuminate\Auth\GuardHelpers;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\UserProvider;
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 \Illuminate\Contracts\Auth\Authenticatable|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 \Illuminate\Http\Request $request * @return $this */
public function setRequest(Request $request) {
$this->request = $request;
return $this;
}
}
複製代碼
在 AppServiceProvider 的 boot 方法添加以下代碼: App\Providers\AuthServiceProvider.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".');
});
.
.
.
複製代碼
在 config\auth.php
的 guards 數組中添加自定義 guard
,一個自定義 guard 包括兩部分: driver
和 provider
.
設置 config\auth.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' => App\Models\User::class,
],
'token' => [
'driver' => 'token',
'model' => App\Models\User::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,
],
],
];
複製代碼
第一次寫這麼多字的文章,寫的很差請多多包涵!!