Net Core教程

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

本文主要是介绍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一个项目中如何支持多种身份认证方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!