首页 > 解决方案 > Laravel Passport 的第一方应用程序密码授予流程

问题描述

我正在使用Laravel Passport将我的 API 的某些部分提供给第三方应用程序。

但是,我也通过自己的第一方 Native Android App 使用自己的 API。因此,我在整个互联网上查看了在这种情况下的最佳实践,但被困在得出结论。

以下是我发现的可能性:

可能性 #01

我可以遵循用户凭据密码授予流程
在这种情况下,我需要将client_secretand传递client_id给授权服务器。为了保证它们的安全,我不能在我的移动应用程序的源代码中编写它们(APK 是可反编译的......)。

所以,我有2个选择。

可能性 #01 - 选择 A

通过我自己的服务器进行代理并在调用 oauth 端点之前注入秘密:

$proxy = Request::create('/oauth/token', 'post', [
    'grant_type' => 'password',
    'client_id' => 1,
    'client_secret' => 'myownclientsecretishere',
    'username' => $username,
    'password' => $password
]);
$proxy->headers->set('Accept', 'application/json');
$response = app()->handle($proxy);

可能性 #01 - 选择 B

使用中间件调用 oauth 端点时注入秘密:

class InjectPasswordGrantSecret
{
    public function handle($request, Closure $next)
    {
        $request->request->add([
            'client_id' => 1,
            'client_secret' => 'myownclientsecretishere'
        ]);
        return $next($request);
    }
}

这些是工作示例,但它们在资源上也很贪婪。我尝试在本地机器上使用Apache 基准测试,但我得到了大约 9 个请求/秒的结果。

可能性 #02

我可以遵循Personal Access Grant
这看起来不像OAuth2中的标准,它允许我们通过任何自定义路由创建令牌,就像这样:

if (! auth()->attempt(compact('username', 'password'))) {
    return error_response(__('auth.failed'));
}
$user = auth()->user();
$token = $user->createToken(null)->accessToken;

使用Apache 基准测试我得到了更好的结果(大约 30 个请求/秒)。

但是,令牌生命周期默认情况下是不可配置的,并且设置为 1 年(请注意,有一些变通方法可以使用自定义提供程序来配置此生命周期)。

我真的想知道这个解决方案是否打算在生产环境中使用。

最初,我使用JWT tymon库,因为我只有自己的应用程序。但是现在我需要让它与第一方和第三方应用程序一起工作,我认为 OAuth2(通过 Laravel Passport)将是一个很好的解决方案......

我希望有人可以帮助我解决这个问题,并解释什么是让它在生产服务器上安全且 [而不是缓慢地] 工作的好解决方案。

标签: phplaravelsecurityoauth-2.0laravel-passport

解决方案


Here is the page that I always refer: https://oauth2.thephpleague.com/authorization-server/which-grant/ enter image description here

It says

We strongly recommend that you use the Authorization Code flow over the Password grant for several reasons. We eliminate the password grant option.

Then, it says clearly in the diagram that you should use

Authorization Code Grant with PKCE

and also indicates that

If the client is a web application that has runs entirely on the front end (e.g. a single page web application) or a native application such as a mobile app you should implement the authorization code grant with the PKCE extension. You can read further in the document.

Additionally, there is a good tutorial here explaining every detail of the flow with an example: https://auth0.com/docs/architecture-scenarios/mobile-api

I hope these help.

PS: When the time I needed to authorize my users in my first party application, I had used password grant by referencing this very chart. However, it seems like it changed and password grant is now not a best practice anymore and is not recommended.


推荐阅读