wg-hyve/keycloak-laravel-guard 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

wg-hyve/keycloak-laravel-guard

Composer 安装命令:

composer require wg-hyve/keycloak-laravel-guard

包简介

Keycloak Guard for Laravel

README 文档

README

This Keycloak lib does not load users from database. Keycloak user UUIDs are usually stored in the sub claim.

Installation

composer require wg-hyve/keycloak-laravel-guard

Configuration

Add your keycloak to your guards and use it in your routes as middleware. That's it for a normal usage.

config/auth.php

return [
    'guards' => [
        // ...
        'cloak' => [
            'driver' => 'keycloak',
            'provider' => 'users',
        ],
        // ...
    ],
];

routes/api.php

Route::any('/acme', [AcmeController::class, 'index'])->middleware(['auth:cloak']);

Extended usage

The KeycloakGuard comes with some methods to keep it easy.

Example usage in requests

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;

class DeleteRequest extends FormRequest
{
    public function authorize(): bool
    {
        return Auth::hasScope('can-delete');
    }

    public function rules(): array
    {
        return [];
    }
}

Other Methods

getTokenFromRequest

Get raw Token from request

token(): ?stdClass

Get encoded Token from request

hasRole(array|string $roles): bool

Proofs if the role or one of the roles is in your client or global roles

scopes(): array

Delivers all scopes

hasScope(string|array $scope): bool

Proofs if the scope or one of the scopes is in your JWT

getRoles(): array

Delivers all roles from your client. Client is delivered in azp claim.

roles(bool $useGlobal = true): array

Delivers all roles (global & client)

User

Saving users in a local database is disabled per default. Execute following steps to enable it. Make sure you read the instructions for the environment variables in your .env.

Configuration

Enable KEYCLOAK_PROVIDE_LOCAL_USER in your environment.

KEYCLOAK_PROVIDE_LOCAL_USER = true

The guard will save user objects from JWTs.

Migrations

Publish und execute migrations.

php artisan vendor:publish --tag=keycloak-migrations

Make adjustments and migrate.

php artisan migrate

User Model

Update your user model in config/auth.php. You can also extend it and add your own user model.

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => \KeycloakGuard\Models\User::class,
    ],
],

You are free to use your user model to extend and define custom relations. Make sure it is compatible with the migration above.

Usage

Receive the User instance with user()

namespace App\Your\Service

use Illuminate\Support\Facades\Auth;
use KeycloakGuard\Models\User;

class AcmeService
{
    public static function getUser(): ?User
    {
        return Auth::user();
    }
}

Environment Variables

KEYCLOAK_REALM_PUBLIC_KEY

Local Public key of your Keycloak instance. You can find it in https://your-keycloak.dev.com/auth/realms/your_realm/

KEYCLOAK_TOKEN_PRINCIPAL_ATTRIBUTE

Should be azp or client_id depending on your Keycloak configuration

KEYCLOAK_IGNORE_RESOURCE_VALIDATION

true or false, auto check if role given with KEYCLOAK_ALLOWED_RESOURCES is in your token

KEYCLOAK_ALLOWED_RESOURCES

role to auto check

KEYCLOAK_REALM_ADDRESS

URL to load public key. Usually https://your-keycloak.dev.com/auth/realms/your_realm/

KEYCLOAK_KEY_CACHE_SECONDS

Cache duration for downloaded public key of your realm.

KEYCLOAK_LEEWAY

You want to set the time offset in seconds if you get Cannot handle token prior to (time) error. Use this if your app and Keycloak timings differ.

KEYCLOAK_PROVIDE_LOCAL_USER

Enable local user processing. The guard will try to store the user in a local database. Default is false.

KEYCLOAK_USER_ID_CLAIM

The user UUID in your JWT. Default is sub claim.

KEYCLOAK_USER_MAIL_CLAIM

The email claim in your JWT. Default is email.

KEYCLOAK_USER_FIRSTNAME_CLAIM

The firstname claim in your JWT. Default is given_name.

KEYCLOAK_USER_LASTNAME_CLAIM

The lastname claim in your JWT. Default is family_name.

Testing

Commands

# run tests with testdox
composer test

# run tests with coverage
composer test:coverage

Docker

Test in docker with coverage after you extended to lib. Don't install xdebug locally 🐌

Create a new source JSON file

Source files are stored in tests/Data Generated tokens are stored in tests/Data/tokens

composer jwt:generate jwt.json access_token
composer jwt:generate jwt_realm_access.json access_token_realm_access
composer jwt:generate jwt.json access_token_has_expire true

wg-hyve/keycloak-laravel-guard 适用场景与选型建议

wg-hyve/keycloak-laravel-guard 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.75k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2023 年 06 月 22 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「keycloak」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 wg-hyve/keycloak-laravel-guard 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 wg-hyve/keycloak-laravel-guard 我们能提供哪些服务?
定制开发 / 二次开发

基于 wg-hyve/keycloak-laravel-guard 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 2.75k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 5
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-06-22