使用 Guards 的 Laravel Passport 多重身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52851208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Passport Multiple Authentication using Guards
提问by Ahmar Arshad
Can we use laravel passport with different guards to authenticate APIs for two different types of users. For example we have driver app for driver user and vendor app for vendor user. Both have their different models Driver and Vendor. How can we use different guards to authenticate both types of users using Laravel Passport?
我们可以使用具有不同保护的 laravel 护照来验证两种不同类型用户的 API。例如,我们为驱动程序用户提供驱动程序应用程序,为供应商用户提供供应商应用程序。两者都有不同的模型驱动程序和供应商。我们如何使用不同的守卫来验证使用 Laravel Passport 的两种类型的用户?
回答by chebaby
Here is an example of auth.php and api.php to start with
下面是一个 auth.php 和 api.php 的例子
config/auth.php
配置/auth.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'driver-api' => [
'driver' => 'passport',
'provider' => 'drivers',
],
'vendor-api' => [
'driver' => 'passport',
'provider' => 'vendors',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'drivers' => [
'driver' => 'eloquent',
'model' => App\Driver::class,
],
'vendors' => [
'driver' => 'eloquent',
'model' => App\Vendor::class,
],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'drivers' => [
'provider' => 'drivers',
'table' => 'password_resets',
'expire' => 60,
],
'vendors' => [
'provider' => 'vendors',
'table' => 'password_resets',
'expire' => 60,
],
],
];
routes/api.php
路线/api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
*/
Route::group(['namespace' => 'Driver', 'prefix' => 'driver/v1', 'middleware' => 'auth:driver-api'], function() {
// define your routes here for the "drivers"
});
Route::group(['namespace' => 'Vendor', 'prefix' => 'vendor/v1', 'middleware' => 'auth:vendor-api'], function() {
// define your routes here for the "vendors"
});
You have to modify this files:
您必须修改此文件:
File: vendor\laravel\passport\src\Bridge\UserRepository.php
文件:vendor\laravel\passport\src\Bridge\UserRepository.php
Copy/Paste getUserEntityByUserCredentialsto make a duplicate of it and name it getEntityByUserCredentials
复制/粘贴getUserEntityByUserCredentials以复制它并将其命名为getEntityByUserCredentials
Then, in the new duplicated function, find the below:
然后,在新的重复函数中,找到以下内容:
$provider = config('auth.guards.api.provider');
And Replace it with:
并将其替换为:
$provider = config('auth.guards.'.$provider.'.provider');
File: vendor\league\oauth2-server\src\Grant\PasswordGrant.php
文件:vendor\league\oauth2-server\src\Grant\PasswordGrant.php
in : validateUsermethod add after $username and $password :
in : validateUser方法在 $username 和 $password 之后添加:
$customProvider = $this->getRequestParameter('customProvider', $request);
if (is_null($customProvider)) {
throw OAuthServerException::invalidRequest('customProvider');
}
And this instead of the original line
而这不是原来的行
$user = $this->userRepository->getEntityByUserCredentials(
$username,
$password,
$this->getIdentifier(),
$client,
$customProvider
);
After doing this you'll be able to pass an extra key/value pair to your access token request, like for example:
执行此操作后,您将能够将额外的键/值对传递给您的访问令牌请求,例如:
grant_type => password,
client_id => someclientid
client_secret => somesecret,
username => someuser,
password => somepass,
client_scope => *,
provider => driver-api // Or vendor-api
I hope this will be helpful for you
我希望这对你有帮助
回答by rharvey
I managed to create multiple auths (with laravel/passport) by using a simple middlware.
我设法使用一个简单的中间件创建了多个身份验证(使用 laravel/passport)。
Step 1: config/auth.php
第 1 步:配置/auth.php
Add your user classes to providers
将您的用户类添加到提供者
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'basic_users', // default
],
],
...
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin_users' => [
'driver' => 'eloquent',
'model' => App\AdminUser::class,
],
'basic_users' => [
'driver' => 'eloquent',
'model' => App\BasicUser::class,
],
],
Clean the cache via CLI
通过 CLI 清理缓存
php artisan config:cache
Step 2: Create middleware
第二步:创建中间件
php artisan make:middleware AdminUserProvider
Open the newly created middleware in app/Http/Middleware and update the hand method like below
在app/Http/Middleware中打开新创建的中间件,更新hand方法如下
public function handle($request, Closure $next)
{
config(['auth.guards.api.provider' => 'admin_users']);
return $next($request);
}
Step 3: Register your middleware
第 3 步:注册您的中间件
Add the newly created middleware to $routeMiddleware
将新创建的中间件添加到 $routeMiddleware
protected $routeMiddleware = [
...
'auth.admin' => \App\Http\Middleware\AdminUserProvider::class,
];
and make sure it's at the top of $middlewarePriority
并确保它位于 $middlewarePriority 的顶部
protected $middlewarePriority = [
\App\Http\Middleware\AdminUserProvider::class,
...
];
Step 4: Add middleware to route
第 4 步:添加中间件到路由
Route::group(['middleware' => ['auth.admin','auth:api']], function() {
Step 5: LoginControllers (AdminUserController & BasicUserController)
第 5 步:登录控制器(AdminUserController 和 BasicUserController)
public function login()
{
$validatedData = request()->validate([
'email' => 'required',
'password' => 'required|min:6'
]);
// get user object
$user = AdminUser::where('email', request()->email)->first();
// do the passwords match?
if (!Hash::check(request()->password, $user->password)) {
// no they don't
return response()->json(['error' => 'Unauthorized'], 401);
}
// log the user in (needed for future requests)
Auth::login($user);
// get new token
$tokenResult = $user->createToken($this->tokenName);
// return token in json response
return response()->json(['success' => ['token' => $tokenResult->accessToken]], 200);
}
In summary:
总之:
The login controllers use Eloquent models to get the user object and then log the user in through Auth::login($user)
登录控制器使用 Eloquent 模型获取用户对象,然后通过 Auth::login($user) 登录用户
Then for future requests that need authentication, the new middleware will change the api auth guard provider to the correct class.
然后对于需要身份验证的未来请求,新的中间件会将 api auth 防护提供程序更改为正确的类。