如何实现API对Identity Server 4的JWT及引用令牌的验证?
验证Identity Server 4的JWT和引用令牌
我来给你梳理下怎么实现API验证Identity Server 4的JWT和引用令牌,结合你给出的JWT头和载荷信息,一步步来:
一、JWT令牌验证
你的JWT用的是RS256非对称签名,头部里的kid字段用来匹配Identity Server发布的公钥,载荷里包含了 issuer、audience、过期时间等关键声明。验证流程主要分两步:签名验证和声明校验。
1. 核心验证逻辑
针对你提供的JWT信息,需要重点验证这些声明:
iss:必须是https://authserv:8097,确保令牌来自可信的Identity Serverexp:检查当前时间是否小于1522088012(令牌过期时间),防止使用过期令牌nbf:确保当前时间大于1522084412(令牌生效时间)aud:验证受众是否包含你的API(你的JWT里有customAPI,这应该是你的API在Identity Server注册的受众标识)scope:如果你的API需要特定权限,比如scope1,要校验这个字段是否存在
2. .NET环境下的代码实现
如果是用ASP.NET Core开发API,可以借助官方的身份验证库来快速实现:
首先安装NuGet包:Microsoft.AspNetCore.Authentication.JwtBearer
然后在Startup/Program.cs里配置验证服务:
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; var builder = WebApplication.CreateBuilder(args); // 添加JWT验证服务 builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = "https://authserv:8097"; // Identity Server的地址 options.Audience = "customAPI"; // 你的API的受众标识 options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = "https://authserv:8097", ValidateAudience = true, ValidAudiences = new[] { "customAPI", "https://authserv:8097/resources" }, // 匹配JWT里的aud列表 ValidateLifetime = true, ValidateIssuerSigningKey = true, // 无需手动配置公钥,库会自动从Identity Server的发现端点获取,通过kid匹配对应密钥 }; }); builder.Services.AddAuthorization(); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); // 你的API路由 app.MapGet("/api/protected", () => "This is protected content") .RequireAuthorization(); app.Run();
二、引用令牌验证
引用令牌不是自包含的,无法直接解析验证,必须调用Identity Server的令牌 introspection 端点来校验令牌的有效性和声明。
1. 核心验证逻辑
- 你的API需要以客户端身份向Identity Server的
/connect/introspect端点发送请求,携带引用令牌和自身的客户端凭证(在Identity Server注册的API客户端ID和密钥) - 解析端点返回的响应,重点检查
active字段是否为true,同时校验aud、scope等声明是否符合要求
2. .NET环境下的代码实现
安装NuGet包:IdentityModel.AspNetCore.OAuth2Introspection
然后配置验证服务:
using IdentityModel.AspNetCore.OAuth2Introspection; var builder = WebApplication.CreateBuilder(args); // 添加引用令牌验证服务 builder.Services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme) .AddOAuth2Introspection(options => { options.Authority = "https://authserv:8097"; options.ClientId = "customAPI"; // 你的API在Identity Server注册的客户端ID options.ClientSecret = "your_api_secret"; // 对应的客户端密钥 options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, // 引用令牌的aud可能不需要严格校验,根据你的业务需求调整 }; }); builder.Services.AddAuthorization(); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); app.MapGet("/api/protected", () => "This is protected content") .RequireAuthorization(); app.Run();
注意事项
- 确保你的API能正常访问Identity Server的发现端点(
/.well-known/openid-configuration)和introspection端点,网络不要有拦截 - JWT验证是本地验证,性能更好;引用令牌需要额外的网络请求,但支持令牌撤销,安全性更高,根据你的业务场景选择
- 不要硬编码公钥或Identity Server的端点地址,尽量通过配置文件读取,方便环境切换
内容的提问来源于stack exchange,提问作者macawman
相关产品推荐
相关产品推荐

