public async Task <IActionResult> OnPostAsync() { (Holuser user, string message) = await holuserService.CheckUser(Username, Password); if (user == null) { Msg = message; } else { string returnUrl = Url.Content("~/"); #region 加入這個使用者需要用到的 宣告類型 Claim Type var claims = new List <Claim> { new Claim(ClaimTypes.Role, "User"), new Claim(ClaimTypes.Name, user.Name), new Claim("TokenVersion", user.TokenVersion.ToString()), }; if (user.Level == 4) { claims.Add(new Claim(ClaimTypes.Role, "Administrator")); } #endregion #region 建立 宣告式身分識別 // ClaimsIdentity類別是宣告式身分識別的具體執行, 也就是宣告集合所描述的身分識別 var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); #endregion #region 建立關於認證階段需要儲存的狀態 var authProperties = new AuthenticationProperties { IsPersistent = true, RedirectUri = this.Request.Host.Value }; #endregion #region 進行使用登入 try { await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); } catch (Exception ex) { string error = ex.Message; } #endregion return(LocalRedirect(returnUrl)); } return(Page()); }
public async Task <IActionResult> Post(LoginRequestDto loginRequestDTO) { APIResult apiResult; await Task.Yield(); if (ModelState.IsValid == false) { apiResult = APIResultFactory.Build(false, StatusCodes.Status200OK, ErrorMessageEnum.傳送過來的資料有問題); return(Ok(apiResult)); } (Holuser user, string message) = await holuserService.CheckUser(loginRequestDTO.Account, loginRequestDTO.Password); if (user == null) { apiResult = APIResultFactory.Build(false, StatusCodes.Status400BadRequest, ErrorMessageEnum.帳號或密碼不正確); return(BadRequest(apiResult)); } string token = GenerateToken(user); string refreshToken = GenerateRefreshToken(user); LoginResponseDto LoginResponseDTO = new LoginResponseDto() { Account = loginRequestDTO.Account, Id = 0, Name = loginRequestDTO.Account, Token = token, TokenExpireMinutes = Convert.ToInt32(configuration["Tokens:JwtExpireMinutes"]), RefreshToken = refreshToken, RefreshTokenExpireDays = Convert.ToInt32(configuration["Tokens:JwtRefreshExpireDays"]), }; apiResult = APIResultFactory.Build(true, StatusCodes.Status200OK, ErrorMessageEnum.None, payload: LoginResponseDTO); return(Ok(apiResult)); }