如何在 codeigniter rest api 中使用刷新令牌?

How to use refresh token in codeigniter rest api?

我是 codeigniter 4 rest api 和 oath 的新手。我能够创建 return 令牌和刷新令牌的登录。我的问题是令牌何时过期。如何使用刷新令牌获取新令牌?我是否必须为此在控制器中创建一个新函数?或者它可以是与登录相同的端点吗?我读过一些文章,我需要将 grant_type、client_id、client_secret 和刷新令牌作为 post 发送。但我不知道将其发送到哪里的端点。我对此完全陌生,请帮助我。谢谢

User.php(控制器)

<?php namespace App\Controllers;

use \App\Libraries\Oauth;
use \OAuth2\Request;
use CodeIgniter\API\ResponseTrait;
use App\Models\UserModel;


class User extends BaseController
{
    use ResponseTrait;

    public function login(){
        $oauth = new Oauth();
        $request = new Request();
        $respond = $oauth->server->handleTokenRequest($request->createFromGlobals());
        $code = $respond->getStatusCode();
        $body = $respond->getResponseBody();
        return $this->respond(json_decode($body), $code);
       
    }

Oauth.php

<?php namespace App\Libraries;

//use \OAuth2\Storage\Pdo;
use \App\Libraries\CustomOauthStorage;


class Oauth{
  var $server;

  function __construct(){
    $this->init();
  }

  public function init(){
    $dsn = getenv('database.default.DSN');
      $username = getenv('database.default.username');
    $password = getenv('database.default.password');

    $storage = new CustomOauthStorage(['dsn' => $dsn, 'username' => $username, 'password' => $password]);
    $this->server = new \OAuth2\Server($storage);
    $this->server->addGrantType(new \OAuth2\GrantType\UserCredentials($storage));
  }
}

当您想使用 CI4 实现 OAuth2 系统时,您可以随意制作它,因为在框架中还没有创建任何东西来这样做。这里看起来你正在为 PHP 使用 bshaffer oauth2 lib(尝试阅读他们的食谱。它个人帮助我在 CI4 项目中实现它很多:https://bshaffer.github.io/oauth2-server-php-docs/cookbook)。

首先,如果您想使用此库制作刷新令牌,您必须将刷新令牌授权类型添加到您的服务器。

$this->server->addGrantType(new \OAuth2\GrantType\UserCredentials($storage));
// this add the refresh token grant type.
// param 'always_issue_new_refresh_token' allows you to catch a new refresh token
// when making a call with a refresh token
$this->server->addGrantType(new \OAuth2\GrantType\RefreshToken($storage, [
    'always_issue_new_refresh_token' => true
]));

然后库会用$respond = $oauth->server->handleTokenRequest($request->createFromGlobals());为你处理。您无需在控制器中添加任何内容。
您可以在 Config/Routes.php 中为刷新令牌调用创建新路由。但是由于您的控制器代码将完全相同,因此最好将其保持在同一路线上。

此外,您将发送到您的 oauth 服务器的 HTTP 请求 必须 具有:

  • Header Content-Type 作为 application/x-www-form-urlencoded
  • 一个body参数grant_type=refresh_token。这就是您的库将如何确定它需要使用刷新令牌过程。
  • 另一个名为 refresh_token 的参数带有实际的刷新令牌

不要忘记阅读 lib 的文档,它很小但非常干净:https://bshaffer.github.io/oauth2-server-php-docs/grant-types/refresh-token/