/ dotnet

authentication in ASP.NET Core

ASP.NET Core 认证与授权

 [AllowAnonymous]
        [HttpPost("login")]
        public async Task<IActionResult> Login(string username, string password)
        {
            if (username == "aaa" && password == "111")
            {

                var user = new { RoleType = 1, Name = "张三丰", ID = 1 };
                string roleId = user.RoleType.ToString();
                var roleName = "";
                switch (roleId)
                {
                    case "1":
                        roleName = "Admin";//管理员
                        break;
                }
                var id = user.ID.ToString();
                var claimIdentity = new ClaimsIdentity("Cookie");
                claimIdentity.AddClaims(new Claim[] {
                      new Claim(ClaimTypes.UserData,roleId),
                      new Claim(ClaimTypes.Role,roleName),
                      new Claim(ClaimTypes.Name,username)
                });

                var authProperties = new AuthenticationProperties{ };

                await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimIdentity), authProperties
                    );

                return new JsonResult(new { Message = "登录成功" }, new Newtonsoft.Json.JsonSerializerSettings());
            }
            else
            {
                return new JsonResult(new { Message = "用户名或密码错误" }, new Newtonsoft.Json.JsonSerializerSettings());
            }
        }

OAuth 认证

Jwt 认证

授权

Reference