Ybd.AbpLite.Jwt 2.0.0

dotnet add package Ybd.AbpLite.Jwt --version 2.0.0
                    
NuGet\Install-Package Ybd.AbpLite.Jwt -Version 2.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Ybd.AbpLite.Jwt" Version="2.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Ybd.AbpLite.Jwt" Version="2.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Ybd.AbpLite.Jwt" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Ybd.AbpLite.Jwt --version 2.0.0
                    
#r "nuget: Ybd.AbpLite.Jwt, 2.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Ybd.AbpLite.Jwt@2.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Ybd.AbpLite.Jwt&version=2.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Ybd.AbpLite.Jwt&version=2.0.0
                    
Install as a Cake Tool

Ybd.AbpLite.Jwt

ABP Framework 的 JWT 模块。引入模块就能用:签发、校验、过期时间配置、自定义 token 内容,全部开箱即用。

只负责"令牌"这一件事,不含用户、密码、登录接口、刷新令牌。谁能登录、怎么校验密码,由你自己的业务决定。

非 ABP 官方包。适用于 ABP 10.7(net10.0)。

安装

dotnet add package Ybd.AbpLite.Jwt

在你的 Host 模块里依赖它:

[DependsOn(typeof(AbpLiteJwtModule))]
public class MyHttpApiHostModule : AbpModule
{
}

配置

配置节名为 Jwt,写在 appsettings.json 或任何其它配置源(单独的 json、环境变量、密钥管理……):

{
  "Jwt": {
    "Issuer": "MyApp",
    "Audience": "MyApp",
    "SecurityKey": "至少 32 个字符的随机字符串",
    "Algorithm": "HS256",
    "Expiration": { "Value": 7, "Unit": "Day" },
    "ClockSkew": { "Value": 30, "Unit": "Second" }
  }
}
键 默认 说明
Issuer / Audience 无 签发者 / 受众;对应的 ValidateIssuer / ValidateAudience(默认 true)为 true 时必填
SecurityKey 无(必填) 签名密钥。生产环境请用环境变量 Jwt__SecurityKey 注入,不要提交到仓库
Algorithm HS256 HS256(密钥 ≥ 32 字符)/ HS384(≥ 48)/ HS512(≥ 64)
Expiration 7 天 token 有效期,数值 + 单位
ClockSkew 30 秒 校验过期时允许的时钟偏移,可填 0
AutoConfigureAuthentication true 是否自动注册 JwtBearer 认证。已有自己的认证方案、只想用签发能力时设为 false

有效期单位

Unit 不区分大小写:

单位 含义
Second 秒
Minute 分
Hour 小时
Day 天
Month 日历月(1 月 31 日 + 1 个月 = 2 月月底,不是固定 30 天)
Year 日历年
"Expiration": { "Value": 2, "Unit": "Hour" }

只写 Value 不写 Unit 时,沿用该配置项自己的默认单位(Expiration 是天,ClockSkew 是秒)。Value 只支持整数,Expiration 必须大于 0。

配置写错会在应用启动时就失败,并说明哪里错(密钥缺失 / 太短、签发者未配置、有效期不为正等),不会等到第一次登录才暴露。修改配置后需要重启应用才生效。

签发令牌

public class AuthAppService : ApplicationService
{
    private readonly IJwtTokenService _jwt;

    public AuthAppService(IJwtTokenService jwt) => _jwt = jwt;

    public LoginOutput Login(LoginInput input)
    {
        // 1. 校验账号密码(你自己的业务)

        // 2. 签发
        var token = _jwt.CreateToken(new JwtModel
        {
            UserId = "42",
            UserName = "tom",
            Roles = ["admin"]
        });

        return new LoginOutput { AccessToken = token.AccessToken, ExpiresAt = token.ExpiresAt };
    }
}

JwtTokenResult 包含 AccessToken、TokenType(固定 Bearer)、ExpiresAt(UTC)、ExpiresIn(秒)。

某次签发想用不同的有效期(例如"记住我"):

_jwt.CreateToken(model, JwtDuration.Of(30, JwtTimeUnit.Day));

需要登录的接口标 [Authorize],按角色限制用 [Authorize(Roles = "admin")]。

自定义 token 里存的内容:继承 JwtModel

JwtModel 自带 UserId、UserName、Roles。需要别的,继承它再加属性,不用手写 claim:

public class MyJwtModel : JwtModel
{
    public Guid TenantId { get; set; }                           // claim 名默认是小驼峰:tenantId
    public int Level { get; set; }
    [JwtClaim("dept")] public string? Department { get; set; }   // 指定 claim 名
    public List<string> Permissions { get; set; } = [];          // 集合
    public ProfileInfo? Profile { get; set; }                    // 复杂对象,以 JSON 存放
    [JwtIgnore] public string? NotInToken { get; set; }          // 不写入 token
}

var token = _jwt.CreateToken(new MyJwtModel { UserId = "42", TenantId = tenantId, Level = 3 });

在任意服务里注入 ICurrentJwtModel<MyJwtModel> 取回自己的对象:

public class OrderAppService : ApplicationService
{
    private readonly ICurrentJwtModel<MyJwtModel> _me;

    public OrderAppService(ICurrentJwtModel<MyJwtModel> me) => _me = me;

    public string Who()
    {
        var me = _me.GetRequired();   // 未登录抛异常;想容忍未登录用 _me.Value(可能为 null)
        return $"{me.UserName} 租户 {me.TenantId} 等级 {me.Level}";
    }
}

支持的属性类型:字符串、数字、布尔、枚举、Guid、DateTime / DateTimeOffset / TimeSpan(及其可空类型)、这些类型的集合、可被 System.Text.Json 序列化的复杂对象。

规则与注意:

  • 只有 public 且可读可写的属性会写入;只读属性不写入(例外:构造时已初始化的只读集合)。
  • claim 名称不能用 iss / aud / exp / nbf / iat / jti(由包自动生成),也不能重名,否则签发时抛出异常并提示改名。
  • token 只有签名没有加密,任何人都能解码查看内容。不要放密码等敏感信息;内容越多 token 越大,只放必需字段。
  • 还原时 token 里没有的字段得到属性的默认值,不会报错(例如用基础 JwtModel 签发的 token,读成 MyJwtModel 时多出来的属性就是默认值)。

也可以不用 JwtModel,自己组装 claim:_jwt.CreateToken(IEnumerable<Claim> claims)。

与 ABP 的集成

引入模块后,ABP 的 AbpClaimTypes(用户 Id、用户名、角色)会对齐到 sub / preferred_username / role,所以 ABP 自带的 ICurrentUser 可以直接用:

CurrentUser.Id          // Guid?:UserId 不是 Guid 时为 null(此时用 ICurrentJwtModel<T>.Value.UserId)
CurrentUser.UserName
CurrentUser.IsInRole("admin")

在不经过 JwtBearer 中间件的场景(WebSocket 握手、回调链接),用 IJwtTokenService.ValidateTokenAsync(token) 手动校验,无效或过期返回 null。

常见问题

问题 说明
改了 SecurityKey 所有已签发的 token 立即失效
多个实例部署 SecurityKey、Issuer、Audience 必须一致
RSA / 其它算法 目前只支持 HMAC(HS256 / HS384 / HS512)。可用 [Dependency(ReplaceServices = true)] + [ExposeServices(typeof(IJwtTokenService))] 替换签发服务,并把 AutoConfigureAuthentication 设为 false 后自行配置认证
刷新令牌 / 退出登录 包不内置(需要存状态)。用你自己的存储配合 JwtModel 里的字段实现
在项目里用了别的认证方案 AutoConfigureAuthentication: false,仍可使用签发能力

许可

MIT

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.0 103 10/29/2026
1.0.0 125 10/17/2026