gpt4 book ai didi

c# - 当方法具有 [AllowAnonymous] 时调用自定义 AuthenticationHandler

转载 作者:行者123 更新时间:2023-11-30 22:53:20 27 4
gpt4 key购买 nike

我正在尝试为我的服务器设置自己的自定义身份验证。但是它会为每个端点调用,即使它在方法上具有 [AllowAnonymous] 属性也是如此。使用我当前的代码,我每次都可以在 HandleAuthenticateAsync 方法中设置断点,即使在允许匿名函数时也是如此。

AddCustomAuthentication 正确添加了 authenticationhandler

        public void ConfigureServices(IServiceCollection services)
{
//services.AddAuthorization();
services.AddAuthentication(options =>
{
// the scheme name has to match the value we're going to use in AuthenticationBuilder.AddScheme(...)
options.DefaultAuthenticateScheme = "scheme";
options.DefaultChallengeScheme = "scheme";
})
.AddCustomAuthentication(o => { });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseAuthentication();

app.UseMvc();
}


...

public class CustomAuthenticationHandler : AuthenticationHandler<CustomAuthenticationOptions>
{

public RvxAuthenticationHandler(
IOptionsMonitor<RvxAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock) : base(options, logger, encoder, clock)
{
}


protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var token = Request.Headers["token"].ToString();

if (string.IsNullOrWhiteSpace(token))
{
return AuthenticateResult.Fail("Invalid Credentials");
}


return AuthenticateResult.Success(new AuthenticationTicket(new System.Security.Claims.ClaimsPrincipal(), "Hi"));
}

最佳答案

将此添加到 HandleAuthenticateAsync 方法的顶部

protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var endpoint = Context.GetEndpoint();
if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null)
{
return Task.FromResult(AuthenticateResult.NoResult());
}

....
}

这是 Microsoft 在 AuthorizeFiler 中使用的内容 - https://github.com/dotnet/aspnetcore/blob/bd65275148abc9b07a3b59797a88d485341152bf/src/Mvc/Mvc.Core/src/Authorization/AuthorizeFilter.cs#L236

它将允许您在 Controller 中使用 AllowAnonymous 属性来绕过您的自定义 AuthenticationHandler

关于c# - 当方法具有 [AllowAnonymous] 时调用自定义 AuthenticationHandler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57299922/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com