You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core中使用自有授权服务器的OAuth2 Bearer令牌

ASP.NET Core 兼容.NET Framework MachineKey加密的OAuth2 Bearer Token验证方案

实现步骤

1. 安装依赖NuGet包

需要先安装以下核心依赖:

  • Microsoft.AspNetCore.Authentication.JwtBearer:JWT Bearer认证核心组件
  • Microsoft.AspNetCore.DataProtection.Extensions:提供数据保护兼容配置能力
  • Microsoft.Owin.Security.Interop:提供与.NET Framework Katana框架的令牌兼容处理能力

2. 配置密钥参数

将原有.NET Framework应用中machineKey对应的validationKey、decryptionKey,以及和老应用保持一致的应用标识,配置到ASP.NET Core项目的appsettings.json中:

{
  "MachineKeyConfig": {
    "ValidationKey": "替换为原有配置的VALIDATION_KEY值",
    "DecryptionKey": "替换为原有配置的DECRYPTION_KEY值",
    "ApplicationName": "替换为和原有.NET Framework应用完全一致的应用标识"
  }
}

3. 配置服务与中间件

以下是.NET 6+ 顶层语句的Program.cs配置示例,.NET 6以下版本的Startup.cs配置逻辑完全一致:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

// 读取machineKey相关配置
var machineKeyConfig = builder.Configuration.GetSection("MachineKeyConfig");
var validationKey = machineKeyConfig["ValidationKey"];
var decryptionKey = machineKeyConfig["DecryptionKey"];
var appName = machineKeyConfig["ApplicationName"];

// 配置数据保护,与.NET Framework machineKey加解密逻辑兼容
builder.Services.AddDataProtection()
    .SetApplicationName(appName)
    .UseCryptographicAlgorithms(new AuthenticatedEncryptorConfiguration
    {
        EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC, // 对应老版本machineKey默认的解密算法
        ValidationAlgorithm = ValidationAlgorithm.HMACSHA1 // 对应你原有配置的validation="SHA1"
    })
    .PersistKeysToFileSystem(new DirectoryInfo(@"C:\your-local-key-storage-path")); // 路径只需确保应用有读写权限即可

// 配置OAuth2 Bearer认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        // 校验规则和原有.NET Framework应用保持一致即可
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromMinutes(5)
        };
        // 注入兼容machineKey的令牌验证器,可直接复用微软Katana项目的开源MachineKey加解密逻辑实现
        options.SecurityTokenValidators.Clear();
        options.SecurityTokenValidators.Add(new MachineKeyCompatibleTokenValidator(validationKey, decryptionKey));
    });

// 注册其他业务服务
builder.Services.AddControllers();

var app = builder.Build();

// 中间件顺序不可修改,必须先执行认证再执行授权
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

如果你原有授权服务器生成的是Katana默认的自定义令牌格式(非标准JWT),可以直接使用Microsoft.Owin.Security.Interop包提供的UseOAuthBearerAuthentication扩展方法,配置方式和.NET Framework几乎完全一致,只需提前完成上述数据保护兼容配置即可。

注意事项

  • 必须确保ApplicationName参数和所有原有.NET Framework应用的配置完全一致,否则即使密钥正确也无法解密令牌
  • 加解密、验签算法必须和原有machineKey的配置完全匹配,若你原有machineKey配置了非默认的decryption属性,需要对应修改EncryptionAlgorithm参数
  • 生产环境不要把密钥硬编码在代码中,建议用环境变量、内部密钥中心等安全方式存储validationKey和decryptionKey

内容的提问来源于stack exchange,提问作者Scott Wilson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:15:10