自定义令牌响应 Laravel Passport

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43146964/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:42:00  来源:igfitidea点击:

Customising token response Laravel Passport

laraveloauth-2.0laravel-passport

提问by Irvin Chan

I am working on an API at the moment and have hit a brick wall. I am using Passport with the 'Password' grant type.

我目前正在开发 API,但遇到了麻烦。我正在使用带有“密码”授权类型的 Passport。

I want to return the user information with the access tokens, however, I am not sure how to.

我想用访问令牌返回用户信息,但是,我不知道如何。

Which class could I implement, edit or extend to get this?.

我可以实现、编辑或扩展哪个类来获得它?

I would like this to be returned:

我想退回这个:

{
    "token_type": "Bearer",
    "expires_in": 31536000,
    "access_token": "lalalalalal",
    "refresh_token": "lalalallala",
    "user": {
        "username": "a username",
        "user_type": "admin"
    }
}

Thanks in advance.

提前致谢。

回答by escapisam

The instructions on how to do this are hinted in the BearerTokenResponseclass (part of the league/oauth2-server package).

有关如何执行此操作的说明在BearerTokenResponse类中(联盟/oauth2-server 包的一部分)中有所提示。

Tested on Laravel 5.7.

在 Laravel 5.7 上测试。

1. Extend the BearerTokenResponseclass, add the extra params you need in the response.

1.扩展BearerTokenResponse类,在响应中添加您需要的额外参数

namespace App\Auth;

use League\OAuth2\Server\Entities\AccessTokenEntityInterface;

class BearerTokenResponse extends \League\OAuth2\Server\ResponseTypes\BearerTokenResponse
{
    /**
     * Add custom fields to your Bearer Token response here, then override
     * AuthorizationServer::getResponseType() to pull in your version of
     * this class rather than the default.
     *
     * @param AccessTokenEntityInterface $accessToken
     *
     * @return array
     */
    protected function getExtraParams(AccessTokenEntityInterface $accessToken): array
    {
        return [
            'user_id' => $this->accessToken->getUserIdentifier(),
        ];
    }
}

2. Create your own PassportServiceProviderclass and override the makeAuthorizationServer()method in order to pass in your own BearerTokenResponseclass.

2. 创建您自己的PassportServiceProvider类并覆盖该makeAuthorizationServer()方法以传入您自己的BearerTokenResponse类。

namespace App\Providers;

use App\Auth\BearerTokenResponse;
use Laravel\Passport\Bridge;
use League\OAuth2\Server\AuthorizationServer;

class PassportServiceProvider extends \Laravel\Passport\PassportServiceProvider
{
    /**
     * Make the authorization service instance.
     *
     * @return \League\OAuth2\Server\AuthorizationServer
     */
    public function makeAuthorizationServer()
    {
        return new AuthorizationServer(
            $this->app->make(Bridge\ClientRepository::class),
            $this->app->make(Bridge\AccessTokenRepository::class),
            $this->app->make(Bridge\ScopeRepository::class),
            $this->makeCryptKey('private'),
            app('encrypter')->getKey(),
            new BearerTokenResponse() // <-- The class you created above
        );
    }
}

3. Add your provider to the providers array in config/app.php

3. 将您的提供者添加到提供者数组中 config/app.php

    /*
     * Application Service Providers...
     */
    App\Providers\PassportServiceProvider::class,

4. Exclude the passport package from laravel auto-discovery in composer.json

4.从laravel自动发现中排除护照包 composer.json

This stops the default PassportServiceProviderclass from being loaded.

这将阻止PassportServiceProvider加载默认类。

    "extra": {
        "laravel": {
            "dont-discover": [
                "laravel/passport"
            ]
        }
    },

Then run composer install.

然后运行composer install

回答by Albert Cloete

Two steps.

两步。

1. Add a new route in your routes file.

1. 在您的路线文件中添加一条新路线。

// routes/api.php

Route::post('oauth/token', 'AuthController@auth');

Keep in mind this will change the route for getting the token from /oauth/tokento /api/oauth/token.

请记住,这将更改从/oauth/token到获取令牌的路线/api/oauth/token

2. Add the controller method.

2. 添加控制器方法。

<?php
// app/Http/Controllers/AuthController.php

namespace App\Http\Controllers;

use App\User;
use Psr\Http\Message\ServerRequestInterface;
use \Laravel\Passport\Http\Controllers\AccessTokenController;

class AuthController extends AccessTokenController
{
    public function auth(ServerRequestInterface $request)
    {
            $tokenResponse = parent::issueToken($request);
            $token = $tokenResponse->getContent();

            // $tokenInfo will contain the usual Laravel Passort token response.
            $tokenInfo = json_decode($token, true);

            // Then we just add the user to the response before returning it.
            $username = $request->getParsedBody()['username'];
            $user = User::whereEmail($username)->first();
            $tokenInfo = collect($tokenInfo);
            $tokenInfo->put('user', $user);

            return $tokenInfo;
    }
}

回答by cyberfly

Another better answer from the web

来自网络的另一个更好的答案

Custom Laravel Passport BearerTokenResponse

自定义 Laravel Passport BearerTokenResponse

https://gist.github.com/messi89/489473c053e3ea8d9e034b0032effb1d

https://gist.github.com/messi89/489473c053e3ea8d9e034b0032effb1d

回答by brandon-estrella-dev

To add custom claims to your Passport token, here is a gist using Passport 8 with Laravel 6

要将自定义声明添加到您的 Passport 令牌,这里是使用 Passport 8 和 Laravel 6 的要点

https://gist.github.com/onamfc/0422da15743918e653888441ba6226ca

https://gist.github.com/onamfc/0422da15743918e653888441ba6226ca

回答by Leo Nogueira

Im using Multi-Auth with passport, so the previous answers didn't help me.

我将多重身份验证与护照一起使用,所以以前的答案对我没有帮助。

After hours of "googling" I found this answer (after-) middleware.

经过数小时的“谷歌搜索”,我找到了这个答案(after-) middleware

My middleware basically gets the result of Passport auth, checks if there is an Bearer inside and append more data to the content.

我的中间件基本上得到 Passport auth 的结果,检查里面是否有一个 Bearer 并将更多数据附加到内容中。

<?php

namespace App\Http\Middleware;

use Closure;

class AppendTokenResponse
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $response =  $next($request);

        $content = json_decode($response->content(), true);

        if (!empty($content['access_token'])) {

            $content['moredata'] = 'some data';

            $response->setContent($content);

        }

        return $response;
    }
}

Now put the new Middleware in $routemiddleware at App/Http/Kernel.php

现在将新的中间件放在 App/Http/Kernel.php 的 $routemiddleware 中

 /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'cors' => \App\Http\Middleware\Cors::class,
        'multiauth' => \SMartins\PassportMultiauth\Http\Middleware\MultiAuthenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'oauth.providers' => \SMartins\PassportMultiauth\Http\Middleware\AddCustomProvider::class,
        'append_auth' =>\App\Http\Middleware\AppendTokenResponse::class,

    ];

Then just register this middleware to Passport Routes in Providers/AuthServiceProvider.php

然后只需将此中间件注册到 Providers/AuthServiceProvider.php 中的 Passport Routes

With Multiauth:

使用多重身份验证:

Route::group(['middleware' => ['oauth.providers','append_auth']], function () {
    Passport::routes(function ($router) {
        return $router->forAccessTokens();
    });
});

I believe regular passport should be (not tested):

我认为普通护照应该(未测试):

Route::group(['middleware' => ['append_auth']], function () {
    Passport::routes();
});