我有一个REST API项目,可提供一些受保护的资源。当用户想要与de API进行交互时,首先必须在其中进行身份验证。
要对用户进行身份验证,API具有单个端点/tokens
,该端点接收凭据并发送Json Web令牌作为响应(如果成功的话)。
现在,我需要在Laravel 5.8 MVC项目中实现一个登录表单,以允许API用户交换Json Web令牌。为此,我想扩展身份验证模块(创建自定义用户提供程序),但是我没有成功。
首先,我创建并注册了新的用户提供程序类:
app / Services / Auth / BeonweUserProvider.php
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable;
class BeonweUserProvider implements UserProvider
{
public function retrieveByCredentials(array $credentials)
{
// Makes an API call and retrive the JWT.
// Return an Authenticatable
}
public function validateCredentials(Authenticatable $user, Array $credentials)
{
// The API did it ...
return true;
}
}
app / Providers / AuthServiceProvider.php
public function boot()
{
$this->registerPolicies();
Auth::provider('BeonweUser', function ($app, array $config) {
$authenticable = 'App\Services\Auth\AuthenticatedUser';
return new BeonweUserProvider($app->make($authenticable));
});
}
config / auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'beonwe',
],
],
'providers' => [
'beonwe' => [
'driver' => 'BeonweUser'
]
]
然后,我创建一个简单的Authenticable User类:
class AuthenticatedUser extends User implements Authenticatable
{
protected $access_token;
public function getAuthIdentifierName()
{
return 'access_token';
}
public function getAuthIdentifier()
{
return $this->{$this->getAuthIdentifierName()};
}
}
当用户提交登录表单时,用户提供程序会成功获取访问令牌,并返回Authenticable的实例。在会话值中,我可以看到正确的JWT
login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d => eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NTE4ODQ4NDIsImV4cCI6MTU1MTkxNzI0MiwidWlkIjoxLCJhaWQiOm51bGwsInR5cGUiOiJzdGFuZGFyZCJ9.G6lmrC-nEZWNWn6XIq9Du_GHtq5xJkNfWM5zpiDg31M
但是Laravel,再次重定向到登录表单。有什么想法吗?
注意:我正在使用Laravel全新安装提供的LoginController。