定制 jeremy379/laravel-openid-connect 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

jeremy379/laravel-openid-connect

Composer 安装命令:

composer require jeremy379/laravel-openid-connect

包简介

OpenID Connect support to the PHP League's OAuth2 Server. Compatible with Laravel Passport.

README 文档

README

PHP 8.2

OpenID Connect for Laravel

OpenID Connect support for Laravel Passport to the PHP League's OAuth2 Server.

This was starter over the work of ronvanderheijden/openid-connect.

Older version than laravel 12 ?

Use tag 2.7.0 https://github.com/jeremy379/laravel-openid-connect/tree/2.7.0

Requirements

Installation

composer require jeremy379/laravel-openid-connect

Now when calling the oauth/authorize endpoint, provide the openid scope to get an id_token. Provide more scopes (e.g. openid profile email) to receive additional claims in the id_token.

The id_token will be returned after the call to the oauth/token endpoint.

Configuration

Add the scope in your AuthServiceProvider in boot() method

If you do not have a AuthServiceProvider, create one in app/Providers and link it in bootstrap/providers.php

public function boot(): void
    {
        Passport::tokensCan(config('openid.passport.tokens_can'));
    }

You may want to combine existing scope and oauth implementation with the open ID connect.

$scopes = array_merge($yourScopes, config('openid.passport.tokens_can'));
Passport::tokensCan($scopes);

Register the authorization view

Laravel passport v13+ does not automatically register the authorization view resulting in an BindingResolutionException when you access the /oauth/authorize endpoint, we need to tell passport which view to use

You have multiple options to link your views:

  • You can add it to your AuthServiceProvider
public function boot(): void
    {
        Passport::authorizationView('auth.oauth.authorize');
    }
  • Or you can add into your 'AppServiceProvider'
public function register(): void
    {
        //...
        $this->app->bind(AuthorizationViewResponse::class, fn() => new SimpleViewResponse('auth.approve'));

    }

An example of views can be found in the view-example/views

Register package passport provider

In boostrap/providers.php, add \OpenIDConnect\Laravel\PassportServiceProvider::class

Alternatively, you can register in in your AppServiceProvider.php

public function register(): void
    {
        //...
        $this->app->register(\OpenIDConnect\Laravel\PassportServiceProvider::class);
    }

And disable auto discovery of Laravel provider in composer json. This will ensure only our provider is used.

"extra": {
        "laravel": {
            "dont-discover": [
                "laravel/passport"
            ]
        }
    },

Then run php artisan package:discover

OpenID need to be linked to a user/identity entity, create that entity

Create an entity class in app/Entities/ named IdentityEntity or UserEntity. This entity is used to collect the claims.

You can customize the entity setup by using another IdentityRepository, this is customizable in the config file.

# app/Entities/IdentityEntity.php
namespace App\Entities;

use League\OAuth2\Server\Entities\Traits\EntityTrait;
use OpenIDConnect\Claims\Traits\WithClaims;
use OpenIDConnect\Entities\Traits\WithCustomPermittedFor;
use OpenIDConnect\Interfaces\IdentityEntityInterface;

class IdentityEntity implements IdentityEntityInterface
{
    use EntityTrait;
    use WithClaims;
    use WithCustomPermittedFor;

    /**
     * The user to collect the additional information for
     */
    protected User $user;

    /**
     * Custom audiences
     * explanation: https://openid.net/specs/openid-connect-core-1_0.html#IDToken
     * When building id token, client id is merged with getPermittedFor()
     */
    public function __construct()
    {
        $this->setPermittedFor([
            'https://api.example.com/v1/resource',
            'custom aud 2'
        ]);
    }

    /**
     * The identity repository creates this entity and provides the user id
     * @param mixed $identifier
     */
    public function setIdentifier($identifier): void
    {
        $this->identifier = $identifier;
        $this->user = User::findOrFail($identifier);
    }

    /**
     * When building the id_token, this entity's claims are collected
     */
    public function getClaims(): array
    {
        return [
            'email' => $this->user->email,
        ];
    }
}

The id token is a JWT and the client should verify the signature.

Here is an example to verify the signature with lcobucci/jwt

$config = Configuration::forSymmetricSigner(
    new \Lcobucci\JWT\Signer\Rsa\Sha256(),
    InMemory::file(base_path('oauth-public.key')) //This is the public key generate by passport. You need to share it.
  );
  
  //Parse the token
  
  $token = $config->parser()->parse($idtoken);
  
  $signatureValid = $config->validator()->validate($token, new \Lcobucci\JWT\Validation\Constraint\SignedWith($config->signer(), $config->signingKey()));

Publishing the config

In case you want to change the default scopes, add custom claim sets or change the repositories, you can publish the openid config using:

php artisan vendor:publish --tag=openid

Using nonce

When nonce is required, you need to pass it as a query parameter to passport.authorizations.approve during authorization step.

Example based on default Passport's authorize.blade.php:

<form method="post" action="{{ route('passport.authorizations.approve').'?nonce='.$request->nonce }}">

Optional Configuration

You can add any JWT Token Headers that you want to the token_headers array in your openid configuration file.

This can be useful to define things like the kid(Key ID). The kid can be any string as long as it can uniquely identify the key you want to use in your JWKS. This can be useful when changing or rolling keys.

Example:

'token_headers' => ['kid' => base64_encode('public-key-added-2023-01-01')]

Additionally, you can configure the JWKS url and some settings for discovery in the config file.

Note: If you define a kid header, it will be added to the JWK returned at the jwks_url (if jwks is enabled in the configuration).

UserInfo endpoint

The package provides an optional GET /oauth/userinfo endpoint as defined by OpenID Connect Core §5.3. It is disabled by default and can be enabled in your published config:

'routes' => [
    // ...
    'userinfo' => true,
],

Once enabled:

  • The endpoint requires a valid Bearer access token (protected by Passport's auth:api guard).
  • It returns the claims from your IdentityEntity::getClaims() filtered to the scopes granted on the token.
  • The sub claim (the user's identifier) is always included.

Example response for a token with the openid email scopes:

{
    "sub": "42",
    "email": "jon.snow@dorne.com"
}

When enabled, the userinfo_endpoint field is automatically included in the OpenID Connect Discovery document (/.well-known/openid-configuration).

Support

You can fill an issue in the github section dedicated for that. I'll try to maintain this fork.

Are you actively using this package and wanna help too? Reach out to me, I'm looking for help to maintain this package.

License

OpenID Connect is open source and licensed under the MIT licence.

jeremy379/laravel-openid-connect 适用场景与选型建议

jeremy379/laravel-openid-connect 是一款 基于 Blade 开发的 Composer 扩展包,目前已累计 435.21k 次下载、GitHub Stars 达 58, 最近一次更新时间为 2023 年 03 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 jeremy379/laravel-openid-connect 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

  • Stars: 58
  • Watchers: 4
  • Forks: 25
  • 开发语言: Blade

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-03-23