我们如何在 Laravel 中实现自定义 API-only 身份验证

这不是一个非常需要答案的问题,但欢迎进一步的建议、答案和建议。我想与全世界分享我是如何解决这个问题的,并希望它能帮助到其他人。

Laravel 附带了几个预先设计的身份验证解决方案,您可以使用一些工匠命令启动它们。这些包括:

  • 标准用户表认证

  • OAuth2(通过 Laravel Passport 包)

  • 基于社交媒体的身份验证(通过 Laravel Socialite 包)

尽管所有这些都很有用,但在这个微服务时代,Laravel 并没有为使用自定义 API 的仅 API 身份验证提供开箱即用的引导程序。

几个月前我遇到了这个问题,我在谷歌和 Stackoverflow 上搜索了答案。我找到了有助于指明方向的有用文章,并引用了这些文章。了解如何将它们粘合在一起并逐步调试以解决问题需要付出一些努力。

提供答案是希望它能帮助其他人 - 以及我自己,因为我将来必须再次做同样的事情。

假设和范围:

  • 您已经创建了自己的 API,例如https://example.com/loginhttps://example.com/logout

  • 你正在运行一个需要身份验证的网站,但不是通过模型和表格或社交媒体

  • 您的 API 管理与表的交互,包括用户登录/注销

  • 您使用 Laravel Passport 附加组件进行 OAuth2 身份验证(感谢@ShuvoJoseph 提醒我注意这一点)


子衿沉夜
浏览 115回答 1
1回答

RISEBY

解决方案涉及七个PHP文件app/Http/Controllers/HomeController.php - 主页控制器;经过身份验证的用户的目的地app/Providers/ApiUserProvider.php - 用于引导和注册登录用户的自定义提供程序,并实现接口 Illuminate\Contracts\Auth\UserProviderapp/CoreExtensions/SessionGuardExtended.php - 自定义保护控制器以登录用户并接收身份验证值并将它们存储在会话数组中;扩展类 Illuminate\Auth\SessionGuardapp/ApiUser - 如果你使用的是 OAuth2(Laravel 的 Passport);公开 OAuth access_token 的自定义用户类;扩展 Illuminate\Auth\GenericUser 并实现接口 Illuminate\Contracts\Auth\Authenticatableconfig/auth.php - 指示 Auth() facade 返回自定义会话保护的 auth 配置app/Providers/AuthServiceProvider.php - auth bootstrapapp/Providers/AppServiceProvider.php - 主应用程序引导程序引用源研究/调查材料供您自己调查并理解它们存在的背景。我并没有声称自己是一个通过自己的魔力从头开始创建解决方案的天才,而是像所有创新者一样,我建立在其他人的努力之上。我的文章的独特卖点是我提供了一个完整的打包解决方案,而引用的来源提供了整体答案的小众部分的解决方案。经过反复试验,他们一起帮助我形成了一个完整的解决方案。了解 config/auth.php 如何影响 AuthManager.php 中的执行的真正有用的文章是https://www.2hatslogic.com/blog/laravel-custom-authentication/未对以下内容进行任何代码修改,但将它们包括在内以确认它们所扮演的角色及其在该过程中的重要性:vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php - 主要授权工厂经理Auth() facade - 默认情况下返回收缩包装的 Illuminate\Auth\SessionGuard 类实例,除非通过 config/auth.php 文件指示它做其他事情 - Auth() 在整个 Laravel 代码中普遍使用来检索会话守卫代码应用程序/Http/Controllers/HomeController.php<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;/**&nbsp;* Handles and manages the home-page&nbsp;*&nbsp;&nbsp;* @category controllers&nbsp;*/class HomeController extends Controller{&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Create a new controller instance.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @return void&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function __construct()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->middleware('auth');&nbsp; &nbsp; }&nbsp; &nbsp; public function index()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; blah&nbsp; &nbsp; }&nbsp; &nbsp; ... other methods ...&nbsp;}应用程序/提供者/ApiUserProvider.php资料来源:将 Laravel 5.8 身份验证与外部 JSON API(创建自己的 ServiceProvider)结合使用https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication基于 API 调用响应的自定义用户身份验证<?phpnamespace App\Providers;use Illuminate\Contracts\Auth\UserProvider;use Illuminate\Contracts\Auth\Authenticatable as UserContract;use App\ApiUser;/**&nbsp;* Delegates API user login and authentication&nbsp;*&nbsp;&nbsp;* @category providers&nbsp;*/class ApiUserProvider implements UserProvider{&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Custom API Handler&nbsp;&nbsp; &nbsp; &nbsp;* Used to request API and capture responses&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp; &nbsp; &nbsp;* @var \Path\To\Your\Internal\Api\Handler&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; private $_oApi = null;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* POST request to API&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp; &nbsp; &nbsp;* @param string&nbsp; $p_url&nbsp; &nbsp; &nbsp; Endpoint URL&nbsp; &nbsp; &nbsp;* @param array&nbsp; &nbsp;$p_arrParam Parameters&nbsp; &nbsp; &nbsp;* @param boolean $p_isOAuth2 Is OAuth2 authenticated request? [Optional, Default=True]&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp; &nbsp; &nbsp;* @return array&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; private function _post(string $p_url, array $p_arrParam, bool $p_isOAuth2=true)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (!$this->_oApi) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->_oApi = new \Path\To\Your\Internal\Api\Handler();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $arrResponse = $this->_oApi->post($p_url, $p_arrParam, $p_isOAuth2);&nbsp; &nbsp; &nbsp; &nbsp; return $arrResponse;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* GET request to API&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp; &nbsp; &nbsp;* @param string $p_url&nbsp; &nbsp; &nbsp;Endpoint URL&nbsp; &nbsp; &nbsp;* @param array $p_arrParam Parameters [Optional, Default = array()]&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp; &nbsp; &nbsp;* @return array&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; private function _get(string $p_url, array $p_arrParam=[], bool $p_isOAuth2=true)&nbsp; &nbsp; {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if (!$this->_oApi) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->_oApi = new \Path\To\Your\Internal\Api\Handler();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; $arrResponse = $this->_oApi->get($p_url, $p_arrParam);&nbsp; &nbsp; &nbsp; &nbsp; return $arrResponse;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Retrieve a user by the given credentials.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param array $p_arrCredentials&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp; &nbsp; &nbsp;* @return \Illuminate\Contracts\Auth\Authenticatable|null&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function retrieveByCredentials(array $p_arrCredentials)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $arrResponse = $this->_post('/login', $p_arrCredentials, false);&nbsp; &nbsp; &nbsp; &nbsp; if ( $arrResponse['result'] ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $arrPayload = array_merge(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $arrResponse['data'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $p_arrCredentials&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $this->getApiUser($arrPayload);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Retrieve a user by their unique identifier.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param mixed $p_id&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp; &nbsp; &nbsp;* @return \Illuminate\Contracts\Auth\Authenticatable|null&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function retrieveById($p_id)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $arrResponse = $this->_get("user/id/{$p_id}");&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if ( $arrResponse['result'] ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $this->getApiUser($arrResponse['data']);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Validate a user against the given credentials.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param \Illuminate\Contracts\Auth\Authenticatable $p_oUser&nbsp; &nbsp; &nbsp;* @param array&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $p_arrCredentials&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp; &nbsp; &nbsp;* @return bool&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function validateCredentials(UserContract $p_oUser, array $p_arrCredentials)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $p_oUser->getAuthPassword() == $p_arrCredentials['password'];&nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Get the api user.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param mixed $p_user&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp; &nbsp; &nbsp;* @return \App\Auth\ApiUser|null&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; protected function getApiUser($p_user)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if ($p_user !== null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new ApiUser($p_user);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }&nbsp; &nbsp; protected function getUserById($id)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $user = [];&nbsp; &nbsp; &nbsp; &nbsp; foreach ($this->getUsers() as $item) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($item['account_id'] == $id) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $user = $item;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return $user ?: null;&nbsp; &nbsp; }&nbsp; &nbsp; protected function getUserByUsername($username)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $user = [];&nbsp; &nbsp; &nbsp; &nbsp; foreach ($this->getUsers() as $item) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($item['email_address'] == $username) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $user = $item;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return $user ?: null;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* The methods below need to be defined because of the Authenticatable contract&nbsp; &nbsp; &nbsp;* but need no implementation for 'Auth::attempt' to work and can be implemented&nbsp; &nbsp; &nbsp;* if you need their functionality&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function retrieveByToken($identifier, $token) { }&nbsp; &nbsp; public function updateRememberToken(UserContract $user, $token) { }&nbsp; &nbsp;&nbsp;}应用程序/CoreExtensions/SessionGuardExtended.php资料来源:扩展 Laravel 5.2 SessionGuard将 Laravel 5.8 身份验证与外部 JSON API(创建自己的 ServiceProvider)结合使用<?phpnamespace App\CoreExtensions;use Illuminate\Auth\SessionGuard;use Illuminate\Contracts\Auth\Authenticatable;/**&nbsp;* Extended SessionGuard() functionality&nbsp;&nbsp;* Provides added functionality to store the OAuth tokens in the session for later use&nbsp;*&nbsp;&nbsp;* @category guards&nbsp;*&nbsp;&nbsp;* @see https://stackoverflow.com/questions/36087061/extending-laravel-5-2-sessionguard&nbsp;*/class SessionGuardExtended extends SessionGuard{&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Log a user into the application.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @param&nbsp; \Illuminate\Contracts\Auth\Authenticatable&nbsp; $p_oUser&nbsp; &nbsp; &nbsp;* @param&nbsp; bool&nbsp; $p_remember&nbsp; &nbsp; &nbsp;* @return void&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function login(Authenticatable $p_oUser, $p_remember = false)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; parent::login($p_oUser, $p_remember);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Writing the OAuth tokens to the session&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; &nbsp; &nbsp; $key = 'authtokens';&nbsp; &nbsp; &nbsp; &nbsp; $this->session->put(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $key,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'access_token' => $p_oUser->getAccessToken(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'refresh_token' => $p_oUser->getRefreshToken(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Log the user out of the application.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @return void&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function logout()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; parent::logout();&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Deleting the OAuth tokens from the session&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; &nbsp; &nbsp; $this->session->forget('authtokens');&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;}应用程序/ApiUser资料来源:使用外部 JSON API 的 Laravel 5.8 身份验证(创建自己的服务提供者)&nbsp;*&nbsp;https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication基于 API 调用响应的自定义用户身份验证<?phpnamespace App;use Illuminate\Auth\GenericUser;use Illuminate\Contracts\Auth\Authenticatable as UserContract;class ApiUser extends GenericUser implements UserContract{&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Returns the OAuth access_token&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp; &nbsp; &nbsp;* @return mixed&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function getAccessToken()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $this->attributes['access_token'];&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; public function getRefreshToken()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return $this->attributes['refresh_token'];&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;}应用程序/提供商/AuthServiceProvider.php<?phpnamespace App\Providers;use Illuminate\Support\Facades\Auth;use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;class AuthServiceProvider extends ServiceProvider{&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Register any authentication / authorization services.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @return void&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function boot()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->registerPolicies();&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; Auth::provider('frank_sinatra', function ($app, array $config) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Return an instance of Illuminate\Contracts\Auth\UserProvider...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new ApiUserProvider();&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }}应用程序/提供者/AppServiceProvider.php资料来源:扩展 Laravel 5.2 SessionGuard笔记:关于此 PHP 文件中编码的更改,存在一些细微的问题。如果您想了解更多,请查看 vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php,尤其是 AuthManager::resolve()。对 config/auth.php 'session' 和 'token' 的引用由硬编码方法 AuthManager::createSessionDriver() 和 AuthManager::createTokenDriver() 提供(如果您知道扩展 AuthManager.php 的方法请告诉我应用程序)AppServiceProvider.php 来拯救!可以在 AppServiceProvider::boot() 中注册自定义守卫,并在执行默认代码之前拦截。我同意上面的第 2 点,但我们不能做一些聪明的事情,比如从 AppServiceProvider 返回自定义会话保护名称或实例,在 AuthManager 的专用公共方法中设置 setCookieJar()、setDispatcher()、setRequest()。 php,它可以挂接到 AppServiceProvider.php 或由 config/auth.php 驱动在 AuthManager.php 中创建自定义会话保护后执行?如果没有 cookie 或会话,则不会通过重定向保留用户的身份。解决此问题的唯一方法是在我们当前的解决方案中的 AppServiceProvider 中包含 setCookieJar()、setDispatcher() 和 setRequest()。<?phpnamespace App\Providers;use Illuminate\Support\ServiceProvider;use Illuminate\Support\Facades\Auth;use App\CoreExtensions\SessionGuardExtended;class AppServiceProvider extends ServiceProvider{&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Register any application services.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @return void&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function register()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Bootstrap any application services.&nbsp; &nbsp; &nbsp;*&nbsp;&nbsp; &nbsp; &nbsp;* @see https://stackoverflow.com/questions/36087061/extending-laravel-5-2-sessionguard&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @return void&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public function boot()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Extending Illuminate\Auth\SessionGuard()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* This is so we can store the OAuth tokens in the session&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; &nbsp; &nbsp; Auth::extend(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'sessionExtended',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; function ($app) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $guard = new SessionGuardExtended(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'sessionExtended',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new ApiUserProvider(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; app()->make('session.store'),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; request()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // When using the remember me functionality of the authentication services we&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // will need to be set the encryption instance of the guard, which allows&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // secure, encrypted cookie values to get generated for those cookies.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (method_exists($guard, 'setCookieJar')) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $guard->setCookieJar($this->app['cookie']);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (method_exists($guard, 'setDispatcher')) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $guard->setDispatcher($this->app['events']);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (method_exists($guard, 'setRequest')) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $guard;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }}配置/auth.php资料来源:https://www.2hatslogic.com/blog/laravel-custom-authentication/<?phpreturn [&nbsp; &nbsp; /*&nbsp; &nbsp; |--------------------------------------------------------------------------&nbsp; &nbsp; | Authentication Defaults&nbsp; &nbsp; |--------------------------------------------------------------------------&nbsp; &nbsp; |&nbsp; &nbsp; | This option controls the default authentication "guard" and password&nbsp; &nbsp; | reset options for your application. You may change these defaults&nbsp; &nbsp; | as required, but they're a perfect start for most applications.&nbsp; &nbsp; |&nbsp; &nbsp; */&nbsp; &nbsp; 'defaults' => [&nbsp; &nbsp; &nbsp; &nbsp; //'guard' => 'web', /** This refers to the settings under ['guards']['web'] */&nbsp; &nbsp; &nbsp; &nbsp; 'guard' => 'webextended', /** This refers to the settings under ['guards']['webextended'] */&nbsp; &nbsp; &nbsp; &nbsp; 'passwords' => 'users', /** This refers to the settings under ['passwords']['users'] */&nbsp; &nbsp; ],&nbsp; &nbsp; /*&nbsp; &nbsp; |--------------------------------------------------------------------------&nbsp; &nbsp; | Authentication Guards&nbsp; &nbsp; |--------------------------------------------------------------------------&nbsp; &nbsp; |&nbsp; &nbsp; | Next, you may define every authentication guard for your application.&nbsp; &nbsp; | Of course, a great default configuration has been defined for you&nbsp; &nbsp; | here which uses session storage and the Eloquent user provider.&nbsp; &nbsp; |&nbsp; &nbsp; | All authentication drivers have a user provider. This defines how the&nbsp; &nbsp; | users are actually retrieved out of your database or other storage&nbsp; &nbsp; | mechanisms used by this application to persist your user's data.&nbsp; &nbsp; |&nbsp; &nbsp; | Supported: "session", "token"&nbsp; &nbsp; |&nbsp; &nbsp; */&nbsp; &nbsp; 'guards' => [&nbsp; &nbsp; &nbsp; &nbsp; 'web' => [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'driver' => 'session', /** This refers to Illuminate/Auth/SessionGuard */&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'provider' => 'users', /** This refers to the settings under ['providers']['users'] */&nbsp; &nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; 'webextended' => [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'driver' => 'sessionExtended', /** @see app/Providers/AppServiceProvider::boot() */&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'provider' => 'users', /** This refers to the settings under ['providers']['users'] */&nbsp; &nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; &nbsp; &nbsp; 'api' => [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'driver' => 'token', /** This refers to Illuminate/Auth/TokenGuard */&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'provider' => 'users',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'hash' => false,&nbsp; &nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; ],&nbsp; &nbsp; /*&nbsp; &nbsp; |--------------------------------------------------------------------------&nbsp; &nbsp; | User Providers&nbsp; &nbsp; |--------------------------------------------------------------------------&nbsp; &nbsp; |&nbsp; &nbsp; | All authentication drivers have a user provider. This defines how the&nbsp; &nbsp; | users are actually retrieved out of your database or other storage&nbsp; &nbsp; | mechanisms used by this application to persist your user's data.&nbsp; &nbsp; |&nbsp; &nbsp; | If you have multiple user tables or models you may configure multiple&nbsp; &nbsp; | sources which represent each model / table. These sources may then&nbsp; &nbsp; | be assigned to any extra authentication guards you have defined.&nbsp; &nbsp; |&nbsp; &nbsp; | Supported: "database", "eloquent"&nbsp; &nbsp; |&nbsp; &nbsp; */&nbsp; &nbsp; 'providers' => [&nbsp; &nbsp; &nbsp; &nbsp; 'users' => [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'driver' => 'frank_sinatra',&nbsp; /** @see app/Providers/AuthServiceProvider::boot() */&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //'model' => App\User::class,&nbsp; &nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; &nbsp; &nbsp; // 'users' => [&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp;'driver' => 'database',&nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp;'table' => 'users',&nbsp; &nbsp; &nbsp; &nbsp; // ],&nbsp; &nbsp; ],&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; blah&nbsp; &nbsp; ],&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; other settings&nbsp; &nbsp; ],];如何使用此解决方案很简单。总体方法没有变化。换句话说,我们使用 Auth() 门面。使用自定义 API 登录时/login?username=<username>&password=<password>request()->flash();$arrData = request()->all();if ( Auth::attempt($arrData, true) ) {&nbsp; &nbsp; return redirect('home');} else&nbsp; {&nbsp; &nbsp; return back()->withErrors(&nbsp; &nbsp; &nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'username' => "Those credentials can't be found",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'password' => "Those credentials can't be found",&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; );}使用自定义 API 注销时/logoutAuth::logout();return redirect('home');

汪汪一只猫

这种方法的问题是它不处理密码重置,这需要将令牌存储在本地数据库中并且很难覆盖。
打开App,查看更多内容
随时随地看视频慕课网APP