casdoor/casdoor-php-sdk

Casdoor的PHP客户端SDK

v1.3.0 2024-06-13 10:51 UTC

This package is auto-updated.

Last update: 2024-09-13 11:21:10 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License PHP Version Require

Casdoor PHP SDK可以让你轻松地将你的应用程序连接到Casdoor认证系统,无需从头开始。

步骤 1: 使用Composer安装casdoor-php-sdk

在你的PHP应用程序目录中,运行以下命令

composer require casdoor/casdoor-php-sdk

或者使用composer.json添加以下代码

{
    "require": {
        "vendor/package": "*",
    }
}

然后运行composer install使其生效。创建一个OauthTest.Php文件并导入SDK包。

<?php

namespace Casdoor\Tests;

use PHPUnit\Framework\TestCase;
use Casdoor\Auth\Jwt;
use Casdoor\Auth\Token;
use Casdoor\Auth\User;

class OauthTest extends TestCase
{
  public function xxx(){}
}

步骤 2: 配置参数

更多信息,请参阅initConfig()

参考代码

public function initConfig()
  {
    $endpoint = 'http://127.0.0.1:8000';
    $clientId = 'c64b12723aefb65a88ce';
    $clientSecret = 'c0c9d483a87332751b2564635765d71c9f6a2e83';
    $certificate = file_get_contents(dirname(__FILE__) . '/public_key.pem');
    $organizationName = 'built-in';
    $applicationName = 'testApp';
    User::initConfig($endpoint, $clientId, $clientSecret, $certificate, $organizationName, $applicationName);
  }

步骤 3: 获取用户JWT令牌

登录登录页面后,页面将重定向到包含代码和状态的链接,例如:https://forum.casbin.com?code=xxx&state=yyyy 在示例文件中输入代码和状态,调用testGetOauthToken()方法,并解析JWT令牌。

public $code = "cc78dc9953ca6ae6ab58";
public $state = "casdoor";
public function testGetOauthToken()
{
    $this->initConfig();
    $token = new Token();
    $accessToken = $token->getOAuthToken($this->code, $this->state);
    $this->assertIsString($accessToken->getToken());
}

JWT令牌代表用户的身份,并有权调用相关API。

步骤 4: 验证和解析用户令牌

当用户传递JWT令牌时,testParseJwtToken函数调用公钥来验证JWT令牌。如果验证通过,则返回包含用户账户信息的Array对象。

public function testParseJwtToken()
{
    $this->initConfig();
    $token = "eyJhxxxx";	// from testGetOauthToken()
    $jwt = new Jwt();
    $result = $jwt->parseJwtToken($token, User::$authConfig);
    $this->assertIsArray();
}

步骤 5: 更新用户信息

testModifyUser调用应用程序配置(非用户令牌)作为更新权限,对用户信息进行CRUD操作。

public function testModifyUser()
{
    $this->initConfig();
    $user = new User();

    # Delete User
    $user->name = 'user_hn99qa';
    $response = $user->deleteUser($user);
    $this->assertTrue($response);

    # Add User
    $response = $user->addUser($user);
    $this->assertTrue($response);

    # Update User
    $user->phone = 'phone';
    $user->displayName = 'display name';
    $response = $user->updateUser($user);
    $this->assertTrue($response);
}

其他:用户交互

  • User::getUser() ,通过用户名获取用户信息
  • User::getUsers() 获取所有用户信息。
  • User::getUserCount() 获取当前用户数量。