【问题标题】:How to use refresh token in codeigniter rest api?如何在codeigniter rest api中使用刷新令牌?
【发布时间】:2021-02-16 22:32:57
【问题描述】:

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

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));
  }
}

【问题讨论】:

标签: php codeigniter-4


【解决方案1】:

当您想使用 CI4 实现 OAuth2 系统时,您可以随意制作它,因为框架中尚未创建任何内容来执行此操作。在这里,您似乎正在为 PHP 使用 bshaffer oauth2 lib(尝试阅读他们的食谱。它对我个人在 CI4 项目中实现它的帮助很大:https://bshaffer.github.io/oauth2-server-php-docs/cookbook)。

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

$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
]));

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

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

  • 标题Content-Typeapplication/x-www-form-urlencoded
  • 主体参数grant_type=refresh_token。这就是您的库将如何确定它需要使用刷新令牌过程的方式。
  • 另一个名为 refresh_token 的参数带有实际的刷新令牌

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-22
    • 2022-01-21
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2021-12-07
    相关资源
    最近更新 更多