php 我们如何在Laravel中实现自定义的仅API身份验证

mnowg1ta  于 2022-11-28  发布在  PHP
关注(0)|答案(2)|浏览(169)

这不是一个需要答案的问题,但欢迎进一步的建议、答案和建议。我想与世界分享我是如何解决这个问题的,并希望它能帮助其他人。
Laravel提供了几种预先设计的身份验证解决方案,您可以使用一些Artisan命令来启动这些解决方案。

  • 标准用户表验证
  • OAuth2(通过Laravel Passport包)
  • 基于社交媒体的身份验证(通过Laravel Socialite软件包)

尽管所有这些都很有用,但在这个微服务的时代,Laravel并没有为使用自定义API的仅API身份验证提供太多现成的引导程序。
几个月前,我就遇到了这个问题,我搜索了谷歌和Stackoverflow寻找答案。我找到了一些有用的文章,它们帮助我指明了方向,这些文章都被引用了。我花了一些精力来理解如何将它们粘合在一起,并进行分步调试来解决问题。
提供答案是希望它能帮助其他人--和我自己,在那里我必须在未来再次做同样的事情。
假设和范围:

  • 您已经创建了自己的API,如https://example.com/loginhttps://example.com/logout
  • 您运行的网站需要身份验证,但不需要通过模型和表或社交媒体进行身份验证
  • 您的API管理与表的交互,包括用户登录/注销
  • 您使用Laravel Passport插件进行OAuth2身份验证(感谢@ShuvoJoseph提醒我注意此问题)
u1ehiz5o

u1ehiz5o1#

该解决方案涉及七个PHP文件

  • 首页控制器-首页控制器已验证用户的目标
  • app/Providers/ApiUserProvider.php -一个自定义提供程序,用于引导和注册登录用户,并实现接口Illuminate\Contracts\Auth\UserProvider
  • app/CoreExtensions/SessionGuardExtended.php -自定义的guard-controller,用于登录用户并接收认证值,并将其存储在会话数组中;扩展类Illuminate\身份验证\会话保护
  • app/ApiUser -如果您使用的是OAuth2(Laravel的Passport);公开OAuth access_token的自定义用户类;扩展Illuminate\Auth\GenericUser并实现接口Illuminate\Contracts\Auth\Authenticatable
  • config/auth.php -指示Auth()外观返回自定义会话保护的auth配置
  • 验证引导程序
  • app/Providers/AppServiceProvider.php -主应用程序引导程序

源研究/调查材料被引用给你自己调查和理解他们存在的背景上下文。我不声称是一个天才谁创造了解决方案从零开始通过我自己的魔力,而是-像所有的创新者-我建立在别人的努力。我的文章的独特卖点是,我提供了一个完整的打包解决方案,而引用的来源提供了整体答案中利基部分的解决方案。一起,经过多次反复试验,它们帮助我形成了一个完整的解决方案。
要了解config/auth.php如何影响AuthManager.php中的执行,一篇真正有用的文章是https://www.2hatslogic.com/blog/laravel-custom-authentication/
未对以下内容进行代码修改,但将其包括在内是为了确认它们在过程中所扮演的角色及其重要性:

  • 主授权工厂管理器
  • Auth()facade -默认情况下返回收缩 Package 的Illuminate\Auth\SessionGuard类示例,除非通过config/auth.php文件指示它执行其他操作- Auth()在Laravel代码中普遍使用,以检索会话保护

代码
应用程序/HTTP/控制器/家庭控制器. php

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

/**
 * Handles and manages the home-page
 * 
 * @category controllers
 */
class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        blah
    }

    ... other methods ... 

}

应用程序/提供程序/ApiUserProvider. php

资料来源:

<?php
namespace App\Providers;

use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use App\ApiUser;

/**
 * Delegates API user login and authentication
 * 
 * @category providers
 */
class ApiUserProvider implements UserProvider
{
    
    /**
     * Custom API Handler 
     * Used to request API and capture responses
     * 
     * @var \Path\To\Your\Internal\Api\Handler
     */
    private $_oApi = null;
    
    /**
     * POST request to API
     * 
     * @param string  $p_url      Endpoint URL
     * @param array   $p_arrParam Parameters
     * @param boolean $p_isOAuth2 Is OAuth2 authenticated request? [Optional, Default=True]
     * 
     * @return array
     */
    private function _post(string $p_url, array $p_arrParam, bool $p_isOAuth2=true)
    {
        if (!$this->_oApi) {
            $this->_oApi = new \Path\To\Your\Internal\Api\Handler();
        }
        $arrResponse = $this->_oApi->post($p_url, $p_arrParam, $p_isOAuth2);
        return $arrResponse;
    }
    
    /**
     * GET request to API
     * 
     * @param string $p_url     Endpoint URL
     * @param array $p_arrParam Parameters [Optional, Default = array()]
     * 
     * @return array
     */
    private function _get(string $p_url, array $p_arrParam=[], bool $p_isOAuth2=true)
    {   
        if (!$this->_oApi) {
            $this->_oApi = new \Path\To\Your\Internal\Api\Handler();
        }
        $arrResponse = $this->_oApi->get($p_url, $p_arrParam);
        return $arrResponse;
    }
    
    /**
     * Retrieve a user by the given credentials.
     *
     * @param array $p_arrCredentials
     * 
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $p_arrCredentials)
    {
        $arrResponse = $this->_post('/login', $p_arrCredentials, false);
        if ( $arrResponse['result'] ) {
            $arrPayload = array_merge(
                $arrResponse['data'],
                $p_arrCredentials
            );
            return $this->getApiUser($arrPayload);
        }
    }

    /**
     * Retrieve a user by their unique identifier.
     *
     * @param mixed $p_id
     * 
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveById($p_id)
    {
        $arrResponse = $this->_get("user/id/{$p_id}");        
        if ( $arrResponse['result'] ) {
            return $this->getApiUser($arrResponse['data']);
        }
    }

    /**
     * Validate a user against the given credentials.
     *
     * @param \Illuminate\Contracts\Auth\Authenticatable $p_oUser
     * @param array                                      $p_arrCredentials
     * 
     * @return bool
     */
    public function validateCredentials(UserContract $p_oUser, array $p_arrCredentials)
    {
        return $p_oUser->getAuthPassword() == $p_arrCredentials['password'];
    }

    /**
     * Get the api user.
     *
     * @param mixed $p_user
     * 
     * @return \App\Auth\ApiUser|null
     */
    protected function getApiUser($p_user)
    {
        if ($p_user !== null) {
            return new ApiUser($p_user);
        }
        return null;
    }

    protected function getUserById($id)
    {
        $user = [];

        foreach ($this->getUsers() as $item) {
            if ($item['account_id'] == $id) {
                $user = $item;

                break;
            }
        }

        return $user ?: null;
    }

    protected function getUserByUsername($username)
    {
        $user = [];

        foreach ($this->getUsers() as $item) {
            if ($item['email_address'] == $username) {
                $user = $item;

                break;
            }
        }

        return $user ?: null;
    }
    

    /**
     * The methods below need to be defined because of the Authenticatable contract
     * but need no implementation for 'Auth::attempt' to work and can be implemented
     * if you need their functionality
     */
    public function retrieveByToken($identifier, $token) { }
    public function updateRememberToken(UserContract $user, $token) { }
    
}

应用程序/核心扩展/会话保护扩展. php

资料来源:

<?php
namespace App\CoreExtensions;

use Illuminate\Auth\SessionGuard;
use Illuminate\Contracts\Auth\Authenticatable;

/**
 * Extended SessionGuard() functionality 
 * Provides added functionality to store the OAuth tokens in the session for later use
 * 
 * @category guards
 * 
 * @see https://stackoverflow.com/questions/36087061/extending-laravel-5-2-sessionguard
 */
class SessionGuardExtended extends SessionGuard
{
    
    /**
     * Log a user into the application.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $p_oUser
     * @param  bool  $p_remember
     * @return void
     */
    public function login(Authenticatable $p_oUser, $p_remember = false)
    {
        
        parent::login($p_oUser, $p_remember);
        
        /**
         * Writing the OAuth tokens to the session
         */
        $key = 'authtokens';
        $this->session->put(
            $key, 
            [
                'access_token' => $p_oUser->getAccessToken(),
                'refresh_token' => $p_oUser->getRefreshToken(),
            ]
        );
    }
    
    /**
     * Log the user out of the application.
     *
     * @return void
     */
    public function logout()
    {
        parent::logout();
        
        /**
         * Deleting the OAuth tokens from the session
         */
        $this->session->forget('authtokens');        
    }
    
}

应用程序/Api用户

资料来源:

<?php
namespace App;

use Illuminate\Auth\GenericUser;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

class ApiUser extends GenericUser implements UserContract
{
    
    /**
     * Returns the OAuth access_token
     * 
     * @return mixed
     */
    public function getAccessToken()
    {
        return $this->attributes['access_token'];
    }
    
    
    public function getRefreshToken()
    {
        return $this->attributes['refresh_token'];
    }
    
}

应用程序/提供程序/验证服务提供程序. php

<?php
namespace App\Providers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    
    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        
        Auth::provider('frank_sinatra', function ($app, array $config) {
            // Return an instance of Illuminate\Contracts\Auth\UserProvider...

            return new ApiUserProvider();
        });
        
    }
}

应用程序/提供程序/应用程序服务提供程序. php

资料来源:

注意事项:
关于这个PHP文件中的代码更改,有一些细微的问题。如果你想了解更多,请查看vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php,特别是AuthManager::resolve()。
1.对config/auth.php 'session'和'token'的引用由硬编码方法AuthManager::createSessionDriver()和AuthManager::createTokenDriver()提供(请告诉我您是否知道在应用程序中扩展AuthManager.php的方法)

  1. AppServiceProvider:: Boot ()中可以注册自定义保护,并在默认代码执行之前拦截自定义保护。
    1.我同意上面的第2点,但是我们能不能做一些聪明的事情,比如从AppServiceProvider返回自定义会话保护名称或示例,在AuthManager.php中的一个专门的公共方法中设置setCookieJar()、setDispatcher()、setRequest(),在AuthManager.php中创建自定义会话保护之后,可以将其挂接到AppServiceProvider.php中或由config/auth.php驱动执行?
    1.如果没有cookie或会话,用户的身份将无法通过重定向保留。解决此问题的唯一方法是在我们当前的解决方案中的AppServiceProvider中包含setCookieJar()、setDispatcher()和setRequest()。
<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Auth;
use App\CoreExtensions\SessionGuardExtended;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     * 
     * @see https://stackoverflow.com/questions/36087061/extending-laravel-5-2-sessionguard
     *
     * @return void
     */
    public function boot()
    {
        
        /**
         * Extending Illuminate\Auth\SessionGuard()
         * This is so we can store the OAuth tokens in the session
         */
        Auth::extend(
            'sessionExtended',
            function ($app) {
            
                $guard = new SessionGuardExtended(
                    'sessionExtended', 
                    new ApiUserProvider(), 
                    app()->make('session.store'),
                    request()
                );
            
                // When using the remember me functionality of the authentication services we
                // will need to be set the encryption instance of the guard, which allows
                // secure, encrypted cookie values to get generated for those cookies.
                if (method_exists($guard, 'setCookieJar')) {
                    $guard->setCookieJar($this->app['cookie']);
                }

                if (method_exists($guard, 'setDispatcher')) {
                    $guard->setDispatcher($this->app['events']);
                }

                if (method_exists($guard, 'setRequest')) {
                    $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));
                }

                return $guard;
            }
        );
    }
}

配置/验证. php
资料来源:

<?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' => 'web', /** This refers to the settings under ['guards']['web'] */
        'guard' => 'webextended', /** This refers to the settings under ['guards']['webextended'] */
        'passwords' => 'users', /** This refers to the settings under ['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', /** This refers to Illuminate/Auth/SessionGuard */
            'provider' => 'users', /** This refers to the settings under ['providers']['users'] */
        ],
        
        'webextended' => [
            'driver' => 'sessionExtended', /** @see app/Providers/AppServiceProvider::boot() */
            'provider' => 'users', /** This refers to the settings under ['providers']['users'] */
        ],

        'api' => [
            'driver' => 'token', /** This refers to Illuminate/Auth/TokenGuard */
            'provider' => 'users',
            'hash' => false,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | 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' => 'frank_sinatra',  /** @see app/Providers/AuthServiceProvider::boot() */
            //'model' => App\User::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    [
        blah
    ],

    [
        other settings
    ],

];

如何使用此解决方案

非常简单,整个方法没有变化,换句话说,我们使用Auth()外观。
使用自定义API /login?username=<username>&password=<password>登录时

request()->flash();
$arrData = request()->all();

if ( Auth::attempt($arrData, true) ) {
    return redirect('home');
} else  {
    return back()->withErrors(
        [
            'username' => "Those credentials can't be found",
            'password' => "Those credentials can't be found",
        ]
    );
}

使用自定义API /logout注销时

Auth::logout();
return redirect('home');
nukf8bse

nukf8bse2#

这种方法的问题是它不能处理密码重置,密码重置要求将令牌存储在本地数据库中,覆盖起来很麻烦。

相关问题