ASP.Net Core一个项目中如何支持多种身份认证方式

Posted .Neter

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ASP.Net Core一个项目中如何支持多种身份认证方式相关的知识,希望对你有一定的参考价值。

ConfigureServices方法中添加:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme + "1")
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme + "1", options =>
                  {
                      options.LoginPath = "/Home/Login1";
                      options.Cookie.Name = "www1";
                  })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme + "2", options =>
                {
                    options.LoginPath = "/Home/Login2";
                    options.Cookie.Name = "www2";
                })
                .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = "meshop",
                        ValidAudience = "meshop",
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("f47b558d-7654-458c-99f2-13b190ef0111"))
                    };
                });
        }

Configure方法中添加:

//注意要加在UseRouting、UseEndpoints中间件中间
app.UseAuthentication();
app.UseAuthorization();

Cookies1:

        public IActionResult Index1()
        {
            var claimsPrincipal = HttpContext.User;
            if (claimsPrincipal.Identity.IsAuthenticated)
            {
                ViewBag.Name = claimsPrincipal.Identity.Name;
            }
            return View();
        }
        [AllowAnonymous]
        public IActionResult Login1()
        {
            return View();
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Login1(string name)
        {
            List<Claim> claims = new List<Claim> {
                new Claim(ClaimTypes.Name,name)
            };
            ClaimsIdentity identity = new ClaimsIdentity(claims, "ticket");
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme + "1", principal);
            return Redirect("/home/index1");
        }

Cookies2:


        [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme + "2")]
        public IActionResult Index2()
        {
            var claimsPrincipal = HttpContext.User;
            if (claimsPrincipal.Identity.IsAuthenticated)
            {
                ViewBag.Name = claimsPrincipal.Identity.Name;
            }
            return View();
        }
        [AllowAnonymous]
        public IActionResult Login2()
        {
            return View();
        }
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Login2(string name)
        {
            List<Claim> claims = new List<Claim> {
                new Claim(ClaimTypes.Name,name)
            };
            ClaimsIdentity identity = new ClaimsIdentity(claims, "ticket");
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme + "2", principal);
            return Redirect("/home/index2");
        }

Bearer:

        [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
        public string Api()
        {
            string output = string.Empty;
            return "已登录,name:" + HttpContext.User.Identity.Name;
        }
        public string GetApiToken(string name)
        {
            List<Claim> claims = new List<Claim> {
                new Claim(ClaimTypes.Name,name)
            };
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("f47b558d-7654-458c-99f2-13b190ef0111"));
            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                issuer: "meshop"
                , audience: "meshop"
                , claims: claims
                , notBefore: DateTime.UtcNow
                , expires: DateTime.UtcNow.AddMinutes(1)
                , signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
            );
            return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
        }

以上是关于ASP.Net Core一个项目中如何支持多种身份认证方式的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Core 5.0 WebAPI 中的多种身份验证方案

如何在 ASP.NET Core 中将角色添加到 Windows 身份验证

无私分享:ASP.NET CORE 项目实战(第十二章)添加对SqlServerMySqlOracle的支持

选择 webApi 模板时如何将 ASP.Net 身份添加到 Asp.Net Core?

ASP.NET Core 同时支持多种认证方式 | Swagger 支持

如何在 ASP.NET Core 3.1 中启用多重身份验证?