auth: fix JWT default scheme and multi-audience validation
This commit is contained in:
parent
c354cbab78
commit
9f061277c7
1 changed files with 51 additions and 40 deletions
|
|
@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Authentication;
|
|||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Yavsc.Server.Helpers;
|
||||
|
|
@ -80,25 +81,36 @@ public static class ServiceExtensions
|
|||
?? throw new InvalidOperationException(
|
||||
"Site:Authority is required to configure Yavsc JWT Bearer authentication.");
|
||||
|
||||
|
||||
string[] audiences = configuration.GetSection("Site").GetSection("Audience").Get<string[]>() ?? Array.Empty<string>();
|
||||
AuthenticationBuilder result = builder;
|
||||
foreach (var audience in audiences)
|
||||
var audiences = configuration.GetSection("Site").GetSection("Audience").Get<string[]>()
|
||||
?? Array.Empty<string>();
|
||||
if (audiences.Length == 0)
|
||||
{
|
||||
result = builder.AddJwtBearer(schemeName, options =>
|
||||
throw new InvalidOperationException(
|
||||
"Site:Audience must contain at least one value to configure Yavsc JWT Bearer authentication.");
|
||||
}
|
||||
|
||||
// Defensive: if the caller used AddAuthentication() without defaults,
|
||||
// make sure JWT challenge/authenticate has a valid fallback scheme.
|
||||
builder.Services.PostConfigure<AuthenticationOptions>(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme ??= schemeName;
|
||||
options.DefaultChallengeScheme ??= schemeName;
|
||||
});
|
||||
|
||||
var result = builder.AddJwtBearer(schemeName, options =>
|
||||
{
|
||||
options.IncludeErrorDetails = true;
|
||||
options.Authority = authority;
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateAudience = true,
|
||||
ValidAudience = audience,
|
||||
ValidAudiences = audiences,
|
||||
RoleClaimType = YavscConstants.RoleClaimType,
|
||||
NameClaimType = YavscConstants.NameClaimType,
|
||||
};
|
||||
options.MapInboundClaims = true;
|
||||
options.ClaimsIssuer = authority;
|
||||
options.Audience = audience;
|
||||
options.Audience = audiences[0];
|
||||
|
||||
// Dev: every Yavsc resource service (Yavsc.Api, Yavsc.Blogs,
|
||||
// Yavsc.Org itself) validates JWTs against the OP that runs
|
||||
|
|
@ -124,7 +136,6 @@ public static class ServiceExtensions
|
|||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue