gpt4 book ai didi

asp.net-mvc - 在ASP.NET Core中使用多种身份验证方案

转载 作者:行者123 更新时间:2023-12-04 19:30:57 25 4
gpt4 key购买 nike

我已经使用ASP.NET Core开发了Web API,并且我需要能够对同一服务使用基本身份验证和承载身份验证方案。
由于某种原因,它不起作用:它始终将调用视为承载者。
这是我的代码:

这是我在 Controller 中拥有的属性:

[Authorize(ActiveAuthenticationSchemes = "Basic,Bearer")]
[ResponseCache(NoStore = true, Duration = 0, VaryByHeader = "Authorization")]

这是我的startup.cs:

这部分是针对基本身份验证的:
   app.UseBasicAuthentication(new BasicAuthenticationOptions
{
AutomaticAuthenticate = false,
AutomaticChallenge = false,
Realm = "test",
Events = new BasicAuthenticationEvents
{
OnValidateCredentials = context =>
{
if (svc.IsValidCredential(context.Username, context.Password))
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, context.Username),
new Claim(ClaimTypes.Name, context.Username)
};

context.Ticket = new AuthenticationTicket(
new ClaimsPrincipal(
new ClaimsIdentity(claims, context.Options.AuthenticationScheme)),
new AuthenticationProperties(),
context.Options.AuthenticationScheme);
}

return Task.FromResult<object>(null);
}
}
});

和这段用于承载身份验证的代码:
    app.UseAPIKeyAuthentication(new BearerApiKeyOptions
{
AuthenticationScheme = BearerApiKeySchema,
AutomaticAuthenticate = false
});

最佳答案

您可以查看this以获得来自官方Microsoft GitHub的一些引用。

我的用例略有不同,我需要结合使用Cookie和Windows身份验证。您将需要使用PolicyBuilder来强制执行“需要身份验证”部分。

在ConfigureServices方法上:

            // add additional authorisation for cookie
services.AddAuthorization(options =>
{
options.AddPolicy("CookiePolicy", policy =>
{
policy.AddAuthenticationSchemes("NTLM", "MyCookie"); // order does matter. The last scheme specified here WILL become the default Identity when accessed from User.Identity
policy.RequireAuthenticatedUser();
});
});

在配置方法上:
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookie",
LoginPath = new PathString("/Account/Login/"),
AccessDeniedPath = new PathString("/Account/AccessDenied/"),
AutomaticAuthenticate = false, // this will be handled by the authorisation policy
AutomaticChallenge = false // this will be handled by the authorisation policy
});

在 Controller 上:
        [Authorize("CookiePolicy")] // will check policy with the required authentication scheme (cookie in this case)
public IActionResult AuthorisedPageCookie()
{
return View();
}

关于asp.net-mvc - 在ASP.NET Core中使用多种身份验证方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43800763/

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