gpt4 book ai didi

c# - 如何在 .NET Core 2 中设置 AuthenticationScheme 和 AutomaticAuthenticate?

转载 作者:太空宇宙 更新时间:2023-11-03 22:54:14 24 4
gpt4 key购买 nike

我尝试按照本指南在 .NET core 2 中运行测试时允许用户登录

http://geeklearning.io/how-to-deal-with-identity-when-testing-an-asp-net-core-application/

它说我应该像这样为测试目的配置身份验证中间件:

public class TestAuthenticationOptions : AuthenticationOptions  
{
public virtual ClaimsIdentity Identity { get; } = new ClaimsIdentity(new Claim[]
{
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", Guid.NewGuid().ToString()),
new Claim("http://schemas.microsoft.com/identity/claims/tenantid", "test"),
new Claim("http://schemas.microsoft.com/identity/claims/objectidentifier", Guid.NewGuid().ToString()),
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname", "test"),
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname", "test"),
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn", "test"),
}, "test");

public TestAuthenticationOptions()
{
this.AuthenticationScheme = "TestAuthenticationMiddleware";
this.AutomaticAuthenticate = true;
}
}

这是行不通的,因为 AuthenticationOptions 类已经从 .NET Core 2 中的 AuthenticationOptions 实例中删除了 AuthenticationSchemeAutomaticAuthenticate 属性 cf。 https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x#setting-default-authentication-schemes

所以现在我不知道如何在测试中登录以在 .NET Core 2 中工作。

最佳答案

您可以在 startup.cs 中设置配置选项

services.AddAuthentication(config => {
this.AuthenticationScheme = "TestAuthenticationMiddleware";
this.AutomaticAuthenticate = true;
});

我在 .net core 2.0 中找到的大多数代码都使用这种方式来配置 AuthenticationOptions .但是,如果您需要创建自己的 AuthenticationOptions类和使用。您可以制定自己的方案,这意味着您还需要制定 AuthenticationHandler<TestAuthenticationOptions>类(我们称之为 TestAuthenticationHandler )并将其添加为方案。

services.AddAuthentication(config => {
this.AuthenticationScheme = "TestAuthenticationMiddleware";
this.AutomaticAuthenticate = true;
})
.AddScheme<TestAuthenticationHandler, TestAuthenticationOptions>("TestAuthenticationMiddleware", o => {});

关于c# - 如何在 .NET Core 2 中设置 AuthenticationScheme 和 AutomaticAuthenticate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46206788/

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