您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關使用Laravel Auth怎么自定義接口API用戶認證,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
實現代碼如下:
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
Illuminate\Auth\DatabaseUserProvider
直接通過數據庫表來獲取認證模型.
EloquentUserProvider
Illuminate\Auth\EloquentUserProvider
通過 eloquent 模型來獲取認證模型
根據上面的知識,可以知道要自定義一個認證很簡單。
自定義 Provider
創建一個自定義的認證模型,實現 Authenticatable 接口;
App\Auth\UserProvider.php
<?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; } }
Authenticatable 接口:
Illuminate\Contracts\Auth\Authenticatable
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 模型的這些方法可以修改一些設置。
實現自定義認證模型
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 調用. 代碼就不方便透漏了.
Guard 接口
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);
StatefulGuard 接口
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.
RequestGuard
Illuminate\Auth\RequestGuard
RequestGuard 是一個非常簡單的 guard. RequestGuard 是通過傳入一個閉包來認證的。可以通過調用 Auth::viaRequest 添加一個自定義的 RequestGuard.
SessionGuard
Illuminate\Auth\SessionGuard
SessionGuard 是 Laravel web 認證默認的 guard.
TokenGuard
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, ], ], ];
使用 方式:
上述就是小編為大家分享的使用Laravel Auth怎么自定義接口API用戶認證了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。