首页 > 解决方案 > ASP.NET Core 3 中的多种身份验证类型

问题描述

对于 Web 用户,我正在做基于 Cookie 的身份验证,而对于 IOT 设备,我正在做 JWT Auth。但我也有几个供 Web 和 IOT 用户使用的 API。

如果存在 Cookie,我希望它使用 Cookie/身份验证,如果存在承载,则使用 JWT 验证。实际上,它可能必须同时尝试。

我可以让它们单独工作,即 Cookie Auth 或 JWT Auth,但不能同时使用!

以下是我的 .Net Core 2.2 应用程序的代码片段,它完全符合我的需要。

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)  
                .AddCookie() 
                .AddJwtBearer(cfg =>
                {
                    cfg.RequireHttpsMetadata = false;
                    cfg.SaveToken = true;
                    cfg.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidIssuer = Configuration["JwtIssuer"],
                        ValidAudience = Configuration["JwtIssuer"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
                    };
                });

我在 .Net Core 2.2 中也有这个。

    services.AddMvc(config =>
                {
                        var defaultPolicy = new AuthorizationPolicyBuilder(new[] { JwtBearerDefaults.AuthenticationScheme, IdentityConstants.ApplicationScheme, CookieAuthenticationDefaults.AuthenticationScheme })
                                        .RequireAuthenticatedUser()
                                        .Build();
                        config.Filters.Add(new AuthorizeFilter(defaultPolicy));
                 });

有人可以帮助我们解决 .Net Core 3 中的变化以及我如何解决这个问题。

标签: c#asp.net-identityasp.net-core-3.0

解决方案


推荐阅读