smskin/laravel-identity-service-client

dev-main 2022-07-22 15:02 UTC

This package is auto-updated.

Last update: 2024-09-22 19:30:40 UTC


README

身份服务是一种服务,允许您通过一个常见的远程服务器在Laravel应用程序中组织授权。这允许您组织一个具有端到端授权的多服务架构。

身份服务库由两部分组成

安装

  1. 运行 composer require smskin/laravel-identity-service-client
  2. 运行 php artisan vendor:publish --tag=identity-service-client
  3. 使用配置文件夹和环境的 identity-service-client.php 配置身份服务客户端
  4. 修改创建用户表迁移文件
  5. 运行 php artisan migrate

迁移

如果用户使用正确的jwt打开网站,将自动创建用户。您必须更改用户表以支持可空字段。

通常我会删除除id和日期之外的所有列,因为它们不需要(授权通过远程服务器进行)。例如

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->timestamps();
});

环境

  1. IDENTITY_SERVICE_CLIENT_HOST - 身份服务的公共地址 (https://github.com/smskin/laravel-idenity-service)
  2. IDENTITY_SERVICE_CLIENT_DEBUG - 认证守卫的调试模式
  3. IDENTITY_SERVICE_CLIENT_API_TOKEN - 管理功能的密钥 (管理API - https://github.com/smskin/laravel-idenity-service)

配置

您可以通过 identity-service-client.php 文件配置库。

    • 模型
      • 用户 - 用户模型的类。您可以使用您的用户模型类覆盖它。您必须实现 HasIdentity 合同并实现 IdentityTrait 特性
  • 作用域
    • 初始 - 接收基本用户数据的初始jwt作用域
    • uses - 使用此服务的范围数组(安装此库的服务)。例如,用于管理身份服务的服务使用 Scope::IDENTITY_SERVICE_LOGIN 范围

用户模型示例

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use SMSkin\IdentityServiceClient\Models\Contracts\HasIdentity;
use SMSkin\IdentityServiceClient\Models\Traits\IdentityTrait;

class User extends Authenticatable implements HasIdentity
{
    use HasApiTokens, HasFactory, Notifiable;
    use IdentityTrait;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'identity_uuid',
        'name',
    ];
}

使用

此库注册了2个守卫

  • identity-service-client-jwt
  • identity-service-client-session

您可以使用它与 auth 中间件(例如:auth:identity-service-client-jwt)一起使用,或通过 auth.php 配置文件将其绑定到已存在的守卫。

例如

...
'guards' => [
    'web' => [
        'driver' => 'identity-service-client-session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'identity-service-client-jwt',
        'provider' => 'users',
    ],
],
...

用户有 hasScope 方法来检查jwt中所需的作用域。

Gate::define('viewNova', function (User $user) {
    return $user->hasScope(Scopes::IDENTITY_SERVICE_LOGIN);
});

未知可用作用域的授权逻辑

  1. 守卫尝试使用电子邮件凭据和初始作用域 (identity-service-client.scopes.initial) 登录
  2. 守卫接收JWT
  3. 守卫调用 /identity-service/api/identity/scopes 方法以接收可用用户作用域
  4. 守卫通过使用作用域 (identity-service-client.scopes.uses) 过滤可用作用域
  5. 守卫调用 /identity-service/api/auth/jwt/refresh 方法以使用使用作用域刷新令牌
  6. 守卫接收用于在服务中使用的正确JWT