gpt4 book ai didi

c# - 如何为 ActiveAuthenticationSchemes 设置默认值?

转载 作者:太空狗 更新时间:2023-10-30 00:37:44 26 4
gpt4 key购买 nike

在我的 ASP.Net Core 2 项目中,我有一个要插入的自定义 AuthenticationHandler 中间件。

public class BasicAuthenticationMiddleware : AuthenticationHandler<AuthenticationSchemeOptions>
{
public BasicAuthenticationMiddleware(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var principal = new GenericPrincipal(new GenericIdentity("User"), null);
var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), "BasicAuth");
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}

在我的初创公司中,我有以下内容:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "BasicAuth";
options.DefaultChallengeScheme = "BasicAuth";
options.AddScheme("BasicAuth", x => {
x.DisplayName = "BasicAuthenticationMiddleware";
x.HandlerType = typeof(BasicAuthenticationMiddleware);
});
});
}

最后是我的 View Controller :

[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values/Works
[HttpGet]
[Route("Works")]
[Authorize(ActiveAuthenticationSchemes = "BasicAuth")]
public string Works()
{
return "works";
}

// GET api/values/DoesNotWork
[HttpGet]
[Route("DoesNotWork")]
[Authorize]
public string DoesNotWork()
{
return "does not work";
}

}

当我将 ActiveAuthenticationSchemes 指定为我的方案名称时,我的身份验证器 HandleAuthenticateAsync 将被调用,否则它不会。我有一个演示应用程序在此处显示行为:https://github.com/JohnPAguirre/AuthenticationSchemaProblem

我希望我的 BasicAuthenticationMiddleware 使用我的演示逻辑让所有人登录。我怎样才能使所有请求的 ActiveAuthenticationSchemes 默认为“BasicAuth”?

有人知道我可能遗漏了什么吗?

最佳答案

我确实设法设置了默认身份验证方案通过将我想要的方案设置为 DefaultPolicy 的唯一身份验证方案以进行授权。在您的配置中使用以下内容。我在 AddMvcAddAuthentication 之间使用它并且工作正常。

services.AddAuthorization(config => {
var def = config.DefaultPolicy;
config.DefaultPolicy = new AuthorizationPolicy(def.Requirements,
new List<string>(){ "BasicAuth" });
});

关于c# - 如何为 ActiveAuthenticationSchemes 设置默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45746776/

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