我的移动 API 目前正在使用 IdentityServer,由于各种原因,我需要将其替换为更简单的东西,例如 JWT。 我有一项服务,根据当前标准等提供一些非常基本的 JWT 发布和验证等,但是我在将其插入我当前的 .NET 6 Web API 时遇到问题。
我的TokenService伪代码
public class TokenService : ITokenService
{
public string GetJwt();
public JwtSecurityToken DecodeJwt();
}
我的 Starup.cs 文件目前看起来像这样,多年来一直运行良好。该方法在ConfigureServices中调用:
private void ConfigureIdentityServer(IServiceCollection services)
{
services.AddAuthentication("Bearer")
// Add the IdentityServer access token validation handler into DI for use by the authentication services.
.AddIdentityServerAuthentication(options =>
{
options.Authority = Config.IdentityServerBaseUri;
options.RequireHttpsMetadata = false;
options.ApiName = Config.AppApiName;
options.ApiSecret = Config.ClientSecret;
});
}
我的 AccountController 是这样的:
[HttpGet]
[Authorize]
[CustomClaimFilter]
public IActionResult Get()
{
// Get the claims and return the user account details
}
我希望能够对我的新 JWT 内容进行的操作本质上是使用 IdentityServer 或基于请求客户端提供的标头的 JWT 通过 API 对用户进行身份验证,例如 auth-method: jwt等等
我猜想为了让它发挥作用,我需要做两个主要的改变。首先,类似于上面所示的ConfigureIdentityServer 方法中的AddJwtBearer 的内容,还有一些基于标头在两者之间切换的代码。我很难弄清楚 AddJwtBearer 的内容,而且我不知道从哪里开始切换!
如有任何建议,谢谢。
程序.cs
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(options =>
{
// Set the default scheme to IdentityServer or JWT
options.DefaultAuthenticateScheme = "JwtBearer";
options.DefaultScheme = "JwtBearer";
options.DefaultChallengeScheme = "JwtBearer";
})
.AddJwtBearer("JwtBearer", options =>
{
// Configure JWT Bearer options, such as:
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "https://localhost:7219",
ValidAudience = "https://localhost:7219",
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("my_too_strong_access_secret_key_longer"))
};
})
.AddIdentityServerAuthentication("IdentityServer", options =>
{
// Your existing IdentityServer configuration
});
builder.Services.AddAuthorization();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.Use(async (context, next) =>
{
var authMethod = context.Request.Headers["auth-method"].FirstOrDefault();
if (!string.IsNullOrEmpty(authMethod))
{
// Dynamically set the authentication scheme based on the "auth-method" header
var scheme = authMethod.Equals("jwt", StringComparison.OrdinalIgnoreCase)
? "JwtBearer" // The name of the JWT Bearer scheme you configured
: "IdentityServer"; // The name of the IdentityServer authentication scheme
context.Request.Headers["Authorization"] = new Microsoft.Extensions.Primitives.StringValues($"{scheme} {context.Request.Headers["Authorization"].FirstOrDefault()}");
}
// Continue on to the next middleware
await next.Invoke();
});
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
然后在传递了令牌的[授权]端点中,添加JwtBearer/IdentityServer的标头,它将以您选择的方式进行授权。