Laravel自定义API认证背景与原理
利用 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
位于 Illuminate\Auth\DatabaseUserProvider 命名空间下。
该实现直接通过查询数据库表来获取对应的认证模型数据。
EloquentUserProvider
位于 Illuminate\Auth\EloquentUserProvider 命名空间下。
该实现通过 Eloquent ORM 模型来检索认证模型。
基于上述对 Provider 的理解,自定义认证逻辑变得相对简单。
接下来进行自定义 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。该接口规定了任何用于认证的模型或类必须实现的方法,即若使用自定义类进行认证,需遵循此接口定义规范。
<?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 也是默认 User 模型所使用的特性,它定义了用户模型的默认标识符字段为 'id',密码字段为 password,以及记住我令牌字段为 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 HTTP 客户端工具,用于 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 接口,除了包含基础认证方法外,还增加了支持有状态会话的高级接口。新增接口包括:
// 尝试根据提供的凭证验证用户是否合法
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 默认提供了三种 Guard 实现:RequestGuard、TokenGuard 和 SessionGuard。
RequestGuard
位于 Illuminate\Auth\RequestGuard 命名空间下。
RequestGuard 是一种轻量级的 Guard,通过传入闭包函数来进行认证。可以使用 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,以指定默认使用的 Guard。
<?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,
],
],
];
具体的使用方式如下:

参考文章链接:地址
总结
以上就是本文的全部内容,希望能为各位的学习或工作提供参考价值。如有任何疑问,欢迎留言交流,感谢大家对本站的支持。