admin管理员组文章数量:1432607
How does one wire a custom JwtBearerHandler in .NET7 to this:
builder.Services.AddAuthentication() .AddMicrosoftIdentityWebApi(builder.Configuration);
Alternatively, how would I translate the previous statement into this
builder.Services
.AddAuthentication()
.AddScheme<JwtBearerOptions, CustomJwtHandler>("AzureAd", options => Configuration.Bind("AzureAd", options))
like they do in this example in the answer :
How does one wire a custom JwtBearerHandler in .NET7 to this:
builder.Services.AddAuthentication() .AddMicrosoftIdentityWebApi(builder.Configuration);
Alternatively, how would I translate the previous statement into this
builder.Services
.AddAuthentication()
.AddScheme<JwtBearerOptions, CustomJwtHandler>("AzureAd", options => Configuration.Bind("AzureAd", options))
like they do in this example in the answer : https://stackoverflow/a/68258618/441365
Share Improve this question edited Nov 19, 2024 at 3:13 Qiang Fu 9,4371 gold badge6 silver badges16 bronze badges asked Nov 18, 2024 at 16:41 user441365user441365 4,03411 gold badges46 silver badges63 bronze badges1 Answer
Reset to default 0You could directly replace built-in JwtBearerHandler
by CustomJwtBearerHandler
using DI.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddTransient<JwtBearerHandler, CustomJwtBearerHandler>();
You could test logic like following which will work in the "MicrosoftIdentityWebApi" pipleline.
public class CustomJwtBearerHandler : JwtBearerHandler
{
public CustomJwtBearerHandler(
IOptionsMonitor<JwtBearerOptions> options,
ILoggerFactory logger,
System.Text.Encodings.Web.UrlEncoder encoder,
ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Perform your custom authentication logic here
var result = await base.HandleAuthenticateAsync();
if (result.Succeeded)
{
// Custom logic, e.g., logging or additional validation
var ticket = result.Ticket;
// Example: Reject if a custom claim is missing
if (!ticket.Principal.HasClaim(c => c.Type == "custom-claim"))
{
return AuthenticateResult.Fail("Missing required custom claim.");
}
}
return result;
}
}
本文标签: netAdd custom JwtBearerHandler to quotAddMicrosoftIdentityWebApiquot in net7Stack Overflow
版权声明:本文标题:.net - Add custom JwtBearerHandler to "AddMicrosoftIdentityWebApi" in .net7 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745606573a2665871.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论