定制 stechstudio/laravel-jwt 二次开发

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

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

stechstudio/laravel-jwt

Composer 安装命令:

composer require stechstudio/laravel-jwt

包简介

Helper package that makes it easy to generate, consume, and protect routes with JWT tokens in Laravel

README 文档

README

Laravel JWT Tools

Latest Version on Packagist Software License Tests

This package wraps the excellent lcobucci/jwt library with the following benefits:

  1. JWT facade with helper methods to quickly generate and parse tokens.
  2. Enforces a minimal set of claims for generated tokens, like aud, iss, and exp.
  3. Validate parsed tokens to ensure our required claims are set properly with signature present and valid.
  4. HTTP Middleware to validate a route-specific JWT
  5. Request macro to easily access route-specific JWT claims

Requirements

  • PHP 8.2+
  • Laravel 11+

Quickstart

Installation

composer require stechstudio/laravel-jwt

Simple example

You can generate a simple JWT with the get method.

$jwt = JWT::get('token-id', ['myclaim' => 'somevalue']);

This will generate a token with the ID provided and an array of claims, returning the string token.

Lifetime

The default token expiration is set to 10 minutes which you can configure, or you can specify a custom lifetime value as a third parameter when creating the token:

$jwt = JWT::get('token-id', ['anything' => 'here'], 3600);

This token will expire in one hour. You can also specify the lifetime with Carbon:

$jwt = JWT::get('token-id', ['anything' => 'here'], now()->addMinutes(60));

Signing key

If you are generating a JWT that will be consumed by a different app (very common use case in our company) you can specify the signing key as the fourth parameter.

$jwt = JWT::get('token-id', ['anything' => 'here'], 3600, config('services.otherapp.key'));

Configuration

This package tries to pick sane defaults, while also allowing you to change configs through your .env file.

Signature key

Every token is signed. The JWT_SIGNING_KEY value is used is available, otherwise APP_KEY will be used as the signing key.

Lifetime

Default lifetime is 600 seconds / 10 minutes. You can change the default by specifying the number of seconds as JWT_LIFETIME.

Issuer

The default token issuer (iss claim) is your APP_NAME lowercase. You can specify a different issuer name via JWT_ISSUER.

Audience

The default token audience (aud claim) is your APP_NAME lowercase. You can specify a different audience name via JWT_AUDIENCE.

Building tokens fluently

So far we've looked at the JWT::get() helper method which is super quick for simple needs.

For more control over your token you can create it fluently instead.

You can use any of the methods provided by the underlying Builder class, along with a few new ones like signWith and lifetime.

$token = JWT::identifiedBy('my-token-id')
   ->lifetime(3600)
   ->signWith('custom-signing-key-with-256-bits')
   ->issuedBy("my-app")
   ->permittedFor("receiving-app")
   ->withClaim('myclaim', 'any value')
   ->getToken()
   ->toString();

Parsing

You can parse a JWT string into a token:

$token = JWT::parse("... JWT string ...");

An exception will be thrown if the JWT cannot be parsed.

Validate received tokens

Just as this package has opinions on what a generated token should include, we want to ensure those minimums are set appropriately on any received tokens.

After parsing a received token, simply call isValid or validate, depending on whether you want a boolean result or exceptions thrown. Make sure to pass in the expected token ID.

$token = JWT::parse("... JWT string ...");

$token->isValid('expected-token-id'); // Returns true or false

$token->validate('expected-token-id'); // Throws exceptions for any validation failure

At this point you can be certain that the token:

  1. Is signed, and the signature is verified (using the configured signature key)
  2. Is within the permitted timeframe (has not expired)
  3. Is intended for your app (aud claim matches the configured audience)
  4. Has the expected ID

Validation exceptions

When calling validate('expected-token-id') the following exceptions will be thrown depending on the validation failure:

  • STS\JWT\Exceptions\InvalidSignature
  • STS\JWT\Exceptions\TokenExpired
  • STS\JWT\Exceptions\InvalidAudience
  • STS\JWT\Exceptions\InvalidID
  • STS\JWT\Exceptions\ValidationException will be used for any other types of validation failures.

Retrieving claims

Once you've parsed and validated a token, you can retrieve all token claims with getClaims or simply toArray.

If you'd like to just retrieve your custom payload claims, use getPayload;

// Make our string token
$jwt = JWT::get('token-id', ['foo' => 'bar']);

// Parse it and validate
$token = JWT::parse($jwt)->validate('token-id');

// Ignore registered claims, just get our custom claims
$token->getPayload(); // [ foo => bar ]

Or to retrieve just one claim, use get passing in the name of the claim. You can optionally pass in a default value as the second parameter;

$token->get("foo"); // bar

$token->get("invalid"); // null

$token->get("invalid", "quz"); // quz

Route middleware

We frequently use JWTs to authorize a request. These are sometimes generated and consumed by the same app, but more frequently they are for cross-app authorization.

You can use the included jwt middleware to validate a JWT request. The middleware will look for the JWT in a number of places:

  1. As a request parameter named jwt or token
  2. As a route paramater named jwt or token
  3. In the Authorization header either as Token JWT or Bearer :base64encodedJWT

If a token is found in any of these locations it will be parsed and validated.

Token ID

By default, the token ID will be expected to match the route name.

For example, with this following route the token will need an ID of my.home:

Route::get('/home', [Controller::class, 'home'])->name('my.home')->middleware('jwt');

You can specify the required ID by passing it as a middleware parameter:

Route::get('/home', [Controller::class, 'home'])->middleware('jwt:expected-id');

Access claims on request

All token claims

The Laravel Request has a getClaim macro on it, so you can grab claims from anywhere.

Example when injecting $request into a controller method:

use Illuminate\Http\Request;

class Controller {
    public function home(Request $request)
    {
        echo $request->getClaim('aud'); // The token audience    
    }
}

Custom payload merged

The token payload (custom claims added to the JWT, not part of the core registered claim set) is merged onto the request attributes, so you can access these just like any other request attribute.

If the JWT has a foo claim, you can directly access $request->foo or $request->input('foo') or even request('foo') using the global request helper.

Note: When the payload is merged onto the request, there is a chance that we are stomping on some existing request attributes. Because we really trust the payload in a validated JWT, we prefer this behavior. However if you want to disable set JWT_MERGE_PAYLOAD=false in your .env file.

stechstudio/laravel-jwt 适用场景与选型建议

stechstudio/laravel-jwt 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 137.72k 次下载、GitHub Stars 达 126, 最近一次更新时间为 2019 年 04 月 16 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 137.72k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 126
  • 点击次数: 19
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 126
  • Watchers: 7
  • Forks: 6
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-04-16