xcesaralejandro/canvasoauth

此包为 canvas 和 Laravel 之间的 oauth 提供简单集成。

1.0.2 2022-09-16 21:16 UTC

This package is auto-updated.

Last update: 2024-10-02 16:53:53 UTC


README

canvasoauth 是一个为 Laravel 开发的包,它完整地集成了 Oauth2 凭证流。该包提供了您开始所需的全部内容,并负责存储和续签用户令牌。

要了解更多关于 canvas 的 Oauth2 信息,您可以访问官方 Canvas 文档:[https://canvas.instructure.com/doc/api/file.oauth.html](https://canvas.instructure.com/doc/api/file.oauth.html)

要求

php >= 8.0

Laravel >= 8.0

安装和配置

1.- 将包添加到您的项目中

composer require xcesaralejandro/canvasoauth

2.- 发布提供者

php artisan vendor:publish --provider=xcesaralejandro\canvasoauth\Providers\CanvasOauthServiceProvider --force

3.- 运行迁移

php artisan migrate

4.- 完成配置文件

发布提供者后,您将在 config 文件夹中找到一个名为 canvasoauth.php 的新文件,您需要在那里完成配置。

要填充配置的变量是在 canvas 中添加新的 API 开发者密钥时获得的凭证。在生成凭证的过程中,canvas 会要求您输入重定向点,以下为所有需要输入 URL 的字段:

https://YOUR_DOMAIN_HERE/canvas/code_exchange

回到配置,此时每个部分的填写可能已经很明显了,但我仍会对其进行注释。

VERIFY_SELF_SIGNED_HTTPS => 如果为 false,则允许您执行所需的 HTTP 请求,忽略您的证书是自签名的。

CANVAS_DOMAIN_URL => 您的 Canvas 实例的 URL,例如 https://YOUR_INSTITUTION.instructure.com

CANVAS_CLIENT_ID => canvas 添加新的 API 开发者密钥后生成的 client_id。

CANVAS_CLIENT_SECRET => canvas 添加新的 API 开发者密钥后生成的 client_secret。

使用方法

首先,请注意,此包为您管理授权令牌和检索流程,但在任何情况下都不管理用户。当提到 user_id 时,我们指的是 canvas 提供的。如果您的应用程序有自己的用户管理,请尝试存储本地标识符和授权时获得的 canvas 标识符的字典,否则,您将无法正确获取令牌。

配置工具后,流程从使用凭证构建的预定义链接开始。您可以使用以下外观获取此链接:

use xcesaralejandro\canvasoauth\Facades\CanvasOauth;

CanvasOauth::getInitialAuthenticationUrl()

您可以将此 URL 放入链接、自动重定向或任何您想放置的地方,具体取决于您要构建的应用程序。请记住,这不是身份验证,而是一个获取授权令牌的流程。访问令牌可以无限期地重新生成,因此理想情况下,您应该只要求用户授权一次,然后该包将始终返回一个有效的令牌。

要控制流程,请使用控制器 App\Http\Controllers\CanvasOauthController.php

    public function onFinish(AuthenticatedUser $user, Request $request) : mixed {
        return parent::onFinish($user); // you can skip this, only creates debug log :)
        // At this point the oauth flow has finished successfully and the user has granted permissions.
    }

    public function onRejectedPermission(Request $request) : mixed {
        return parent::onRejectedPermission($request); // you can skip this, only creates debug log :)
        // At this point the user has canceled the grant of permissions.
    }

    public function onError(\Exception $exception) : mixed {
        return parent::onError($exception); // you can skip this, only creates debug log
        // Any error that may arise during the oauth flow will be thrown here
    }

另一方面,您可以使用 CanvasToken 模型来管理令牌,以下是如何操作:

检查用户是否存在令牌

CanvasToken::ExistsForUser(int $user_id) : bool

为特定用户返回令牌,如果令牌已过期,则在后台重新生成。如果查询的用户没有令牌或重新生成令牌时发生错误,则返回 null。

CanvasToken::GetForUser(int $user_id) : ?string