[英]Using multiple authentication schemes in ASP.NET Core
我使用ASP.NET Core开发了Web API,我需要能够为同一服务使用Basic和Bearer身份验证方案。 由于某种原因,它不起作用:它总是将呼叫视为持有者。 这是我的代码:
这是我在控制器中的属性:
[Authorize(ActiveAuthenticationSchemes = "Basic,Bearer")]
[ResponseCache(NoStore = true, Duration = 0, VaryByHeader = "Authorization")]
这是我的startup.cs:
这部分是基本的auth:
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
});
您可以从官方Microsoft GitHub中查看此内容以供参考。
我的用例略有不同,我需要结合使用Cookie和Windows身份验证。 您需要使用PolicyBuilder来强制执行“require authentication”部分。
在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
});
在控制器上:
[Authorize("CookiePolicy")] // will check policy with the required authentication scheme (cookie in this case)
public IActionResult AuthorisedPageCookie()
{
return View();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.