randomstate/laravel-auth-jwt

randomstate/laravel-auth的JWT发行和验证策略

v1.0.3 2020-12-30 17:36 UTC

This package is auto-updated.

Last update: 2024-08-29 05:06:11 UTC


README

这是为randomstate/laravel-auth提供的JWT认证策略。它既负责JWT的发行也负责JWT的认证。

用法

使用Auth Manager进行注册:请参考以下策略服务提供者示例:[https://github.com/randomstate/laravel-auth](https://github.com/randomstate/laravel-auth)

配置

您应该配置您的令牌发行者(Issuer::class),以便根据您的需求生成适当的标准声明(iat、aud等)。

<?php

use \RandomState\LaravelAuth\Strategies\JwtStrategy;
use \RandomState\LaravelAuth\Strategies\Jwt\Issuer;
use \Carbon\CarbonInterval;

class MyServiceProvider extends \Illuminate\Support\ServiceProvider {
    
    public function register() {
        $this->app->resolving(\Illuminate\Auth\AuthManager::class, function($manager) {
           $manager->register('jwt', $this->app->make(JwtStrategy::class));
        });
        
        $this->app->resolving(JwtStrategy::class, function($strategy) {
           $strategy->convertUsing(function(\RandomState\LaravelAuth\Strategies\JwtUser $user) {
              return User::find($user->id()); // assuming you are using Eloquent 
           });
        });
        
        $this->app->bind(Issuer::class, function() {
            $issuer = new Issuer();
            
            $issuer
                ->withIssuer('my_app') // chain and build your configuration
                ->withAudience('my_app')
                ->withExpirationWindow(CarbonInterval::minutes(60))
                ->signTokens(new \Lcobucci\JWT\Signer\Rsa\Sha256(), config('auth.jwt_signing_key')) // your private RSA key in this example
                ;
        });
    }
}

发行令牌

此包会自动从Laravel容器中解析出您的Issuer::class配置。这意味着任何发行的令牌都可以进行检查,无需担心您是否正确配置了一切——只要您在发行令牌和消费它之间不改变laravel绑定Issuer::class的方式,您就可以依赖它的稳定性。

通常,您将想要使用特定的登录路由通过用户名和密码来验证用户。您只需执行任何登录逻辑(通常Laravel可以轻松处理)然后发行并返回JWT令牌,如下所示

<?php

use \Illuminate\Http\Request;
use \App\Http\Controllers\Controller;
use \RandomState\LaravelAuth\Strategies\Jwt\Issuer;
use \Illuminate\Support\Facades\Auth;

class LoginController extends Controller {
    
    public function login(Request $request, Issuer $issuer) {
        $token = $issuer->issue(Auth::user()->getAuthIdentifier());
        
        return response($token);
    }
}

通过JWT进行认证

您可以将JWT令牌作为Authorization: Bearer {token}头信息或作为请求中的token参数提供。当使用LaravelAuth authenticate中间件时,这将自动提取。