我正在try 将我的身份验证内容迁移到Core 2.0,但在使用我自己的身份验证方案时遇到了问题.我在startup中的服务设置如下所示:

var authenticationBuilder = services.AddAuthentication(options =>
{
    options.AddScheme("myauth", builder =>
    {
        builder.HandlerType = typeof(CookieAuthenticationHandler);
    });
})
    .AddCookie();

我在控制器中的登录代码如下所示:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, user.Name)
};

var props = new AuthenticationProperties
{
    IsPersistent = persistCookie,
    ExpiresUtc = DateTime.UtcNow.AddYears(1)
};

var id = new ClaimsIdentity(claims);
await HttpContext.SignInAsync("myauth", new ClaimsPrincipal(id), props);

但当我在控制器或动作过滤器中时,我只有一个身份,而不是经过身份验证的身份:

var identity = context.HttpContext.User.Identities.SingleOrDefault(x => x.AuthenticationType == "myauth");

应对这些变化一直很困难,但我猜我正在这样做.我错了.有什么建议吗?

编辑:这里(本质上)有一个干净的应用程序,不会在用户身上产生两组身份.身份:

namespace WebApplication1.Controllers
{
    public class Testy : Controller
    {
        public IActionResult Index()
        {
            var i = HttpContext.User.Identities;
            return Content("index");
        }

        public async Task<IActionResult> In1()
        {
            var claims = new List<Claim> { new Claim(ClaimTypes.Name, "In1 name") };
            var props = new AuthenticationProperties  { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddYears(1) };
            var id = new ClaimsIdentity(claims);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id), props);
            return Content("In1");
        }

        public async Task<IActionResult> In2()
        {
            var claims = new List<Claim> { new Claim(ClaimTypes.Name, "a2 name") };
            var props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddYears(1) };
            var id = new ClaimsIdentity(claims);
            await HttpContext.SignInAsync("a2", new ClaimsPrincipal(id), props);
            return Content("In2");
        }

        public async Task<IActionResult> Out1()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return Content("Out1");
        }

        public async Task<IActionResult> Out2()
        {
            await HttpContext.SignOutAsync("a2");
            return Content("Out2");
        }
    }
}

和启动:

namespace WebApplication1
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie("a2");

            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

推荐答案

应对这些变化一直很困难,但我猜我正在这样做.我错了.

不要使用AddScheme:这是为编剧设计的低级方法.

如何在ASP.NET Core 2.0中设置多个身份验证方案?

要注册cookies处理程序,只需执行以下操作:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "myauth1";
        })

       .AddCookie("myauth1");
       .AddCookie("myauth2");
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseAuthentication();

        // ...
    }
}

需要注意的是,不能像在1中那样注册多个默认方案.x(这个巨大重构的全部目的是避免同时拥有多个自动身份验证中间件).

如果您确实需要在2.0中模拟这种行为,您可以编写一个自定义中间件,手动调用AuthenticateAsync()并创建一个ClaimsPrincipal,其中包含您需要的所有标识:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = "myauth1";
        })

       .AddCookie("myauth1");
       .AddCookie("myauth2");
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseAuthentication();

        app.Use(async (context, next) =>
        {
            var principal = new ClaimsPrincipal();

            var result1 = await context.AuthenticateAsync("myauth1");
            if (result1?.Principal != null)
            {
                principal.AddIdentities(result1.Principal.Identities);
            }

            var result2 = await context.AuthenticateAsync("myauth2");
            if (result2?.Principal != null)
            {
                principal.AddIdentities(result2.Principal.Identities);
            }

            context.User = principal;

            await next();
        });

        // ...
    }
}

Asp.net相关问答推荐

Razor中的共享本地化资源文件

在每个对象上设置 ClientIDMode = Static 是否有任何缺点(在母版页的 maincontent 上设置)

在 aspx 页面中使用 if else 和 eval

判断 asp.net mvc 4 应用程序中的 ssl 协议、密码和其他属性

如何使用 jQuery 设置 outerHTML

我可以根据角色隐藏/显示 asp:Menu 项吗?

使用 jQuery 验证插件匹配两个字段

IIS 6/ASP.NET Windows 身份验证 list ?

用于链接字符串中的 url 的 C# 代码

您对 Windows Workflow Foundation 有何体验?

ASP.NET MVC4 异步控制器 - 为什么要使用?

如何在 C# 中转换 TryCast?

ASP.NET MVC 2.0 JsonRequestBehavior 全局设置

WebForm_PostBackOptions 文档

在 C# 中动态创建 Json

GZIP 与 DEFLATE 压缩相比有什么优势?

使用 NLog 在 ASP.NET Web API 2.1 中进行全局异常处理?

将 HTML 字符串转换为图像

可以在不 destruct 站点的情况下将 MIME 类型添加到 web.config 吗?

为什么 IFormFile 显示为空,我该如何解决?