问题已解决。
lumen-passport 中可用的多种授权类型,请参见下面的文档参考。链接
https://oauth.net/2/grant-types/
我的问题是生成 client_credentials 用于身份验证令牌的令牌,以便始终返回 Unauthorized 错误。
所以我使用 password 授权类型并生成令牌,并且该令牌在 api 中使用,它将起作用。
http://localhost/api/public/oauth/token
{
"grant_type": "password",
"scope": "*",
"client_id": "client_id",
"client_secret": "client_secret",
"username":"username,
"password":"password"
}
输出是
{
"token_type": "Bearer",
"expires_in": 31622400,
"access_token": "token_here",
"refresh_token": "refresh_token"
}
并且在 api 中使用 access_token,所以它会起作用。
client_credentials授权类型在 lumen-passport 中不可用
但是使用 laravel 护照你可以实现它。
App\Http\Middleware\CheckClientCredentials.php 创建文件
<?php
namespace App\Http\Middleware;
use Closure;
use League\OAuth2\Server\ResourceServer;
use Illuminate\Auth\AuthenticationException;
use Laravel\Passport\Exceptions\MissingScopeException;
use League\OAuth2\Server\Exception\OAuthServerException;
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
class CheckClientCredentials
{
/**
* The Resource Server instance.
*
* @var \League\OAuth2\Server\ResourceServer
*/
private $server;
/**
* Create a new middleware instance.
*
* @param \League\OAuth2\Server\ResourceServer $server
* @return void
*/
public function __construct(ResourceServer $server)
{
$this->server = $server;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param mixed ...$scopes
* @return mixed
* @throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$scopes)
{
$psr = (new DiactorosFactory)->createRequest($request);
try {
$psr = $this->server->validateAuthenticatedRequest($psr);
} catch (OAuthServerException $e) {
//throw new AuthenticationException;
return response('Unauthorized.', 401);
}
$this->validateScopes($psr, $scopes);
return $next($request);
}
/**
* Validate the scopes on the incoming request.
*
* @param \Psr\Http\Message\ResponseInterface $psr
* @param array $scopes
* @return void
* @throws \Laravel\Passport\Exceptions\MissingScopeException
*/
protected function validateScopes($psr, $scopes)
{
if (in_array('*', $tokenScopes = $psr->getAttribute('oauth_scopes'))) {
return;
}
foreach ($scopes as $scope) {
if (! in_array($scope, $tokenScopes)) {
throw new MissingScopeException($scope);
}
}
}
}
bootstrap\app.php更改文件
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
'client_credentials' => App\Http\Middleware\CheckClientCredentials::class
]);
web.php
$app->group(['middleware' => 'client_credentials'], function () use ($app) {
$app->get('/user', ['uses' => 'UserController@getAllUser']);
});
为了令牌
http://localhost/api/public/oauth/token
{
"grant_type": "client_credentials",
"client_id": "client_id",
"client_secret": "client_secret"
}
输出
{
"token_type": "Bearer",
"expires_in": 5400,
"access_token": "access_token_here"
}
该令牌使用了标头,它对我有用。