public bool Set <T>(string name, TimeSpan date, T cookieObject) { var jsonStr = JsonConvert.SerializeObject(cookieObject); return(_encodeCookie ? _cookieHelper.SetProtect(name, jsonStr, date) : _cookieHelper.Set(name, jsonStr, date)); }
public async Task <IActionResult> Login(UserForLogin user, string returnUrl) { if (!ModelState.IsValid) { return(View(user)); } ResultModel result = new ResultModel(); var data = JsonConvert.SerializeObject(user); result = await _callApi.CallAPI(data, new Uri(_config["api"].ToString() + "/auth/login"), "POST"); TempData["IsSuccess"] = result.IsSuccess; TempData["msg"] = result.Message; if (result.IsSuccess) { var LoginUser = new LoginUser(); LoginUser = JsonConvert.DeserializeObject <LoginUser>(result.Data.ToString()); double LoginExpireMinute = Convert.ToDouble(_config["LoginExpireMinute"]); if (user.keepLogin) { LoginExpireMinute = 43200; } var splitToken = LoginUser.access_token.Split('.'); var payloadBase64 = splitToken[1]; payloadBase64 = payloadBase64.PadRight(payloadBase64.Length + (4 - payloadBase64.Length % 4) % 4, '='); var payloadText = Encoding.UTF8.GetString(Convert.FromBase64String(payloadBase64)); var payload = new Payload(); payload = JsonConvert.DeserializeObject <Payload>(payloadText); var Set_access_token = new ResultModel(); var Set_refresh_token = new ResultModel(); var Cookieoptions = new CookieOptions(); Cookieoptions.Expires = DateTime.Now.AddMinutes(LoginExpireMinute); Cookieoptions.SameSite = SameSiteMode.Strict; Cookieoptions.HttpOnly = true; Set_access_token = _cookieHelper.Set("access_token", LoginUser.access_token, Cookieoptions); Set_refresh_token = _cookieHelper.Set("refresh_token", LoginUser.refresh_token, Cookieoptions); if (!Set_access_token.IsSuccess || !Set_refresh_token.IsSuccess) { TempData["msg"] = "Write cookies error."; return(View()); } //建立 Claim,也就是要寫到 Cookie 的內容 var claims = new[] { new Claim("UserId", payload.nameid.ToString()), new Claim("Name", payload.unique_name), }; //建立證件,類似你的駕照或護照 ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); //將 ClaimsIdentity 設定給 ClaimsPrincipal (持有者) ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity); //登入動作 await HttpContext.SignInAsync(principal, new AuthenticationProperties() { //是否可以被刷新 AllowRefresh = true, // 設置了一個 1 天 有效期的持久化 cookie IsPersistent = user.keepLogin, //IsPersistent = false,瀏覽器關閉即刻登出 //用戶頁面停留太久,逾期時間,在此設定的話會覆蓋Startup.cs裡的逾期設定 ExpiresUtc = DateTime.Now.AddMinutes(LoginExpireMinute), }); } if (!result.IsSuccess) { return(View(user)); } if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl)) { return(Redirect(returnUrl));//導到原始要求網址 } else { return(RedirectToAction("Index", "Home"));//到登入後的第一頁,自行決定 } }
public async Task <ResultModel> RefreshMyToken() { var token = new Token(); var result = new ResultModel(); try { //從Cookie取出token var Get_access_token = new ResultModel(); Get_access_token = _cookieHelper.Get("access_token"); if (Get_access_token.IsSuccess) { token.access_token = Get_access_token.Data.ToString(); } var Get_refresh_token = new ResultModel(); Get_refresh_token = _cookieHelper.Get("refresh_token"); if (Get_refresh_token.IsSuccess) { token.refresh_token = Get_refresh_token.Data.ToString(); } var tokenHandler = new JwtSecurityTokenHandler(); var jwtToken = tokenHandler.ReadToken(token.access_token) as JwtSecurityToken; // 將字符串token解碼成token對象 result.IsSuccess = false; result.Message = "Token unauthorized."; var tokenExpireTime = jwtToken.ValidTo.ToLocalTime(); if (tokenExpireTime < DateTime.Now) { var data = JsonConvert.SerializeObject(token); result = await CallAPI(data, new Uri(_config["api"].ToString() + "/auth/RefreshToken"), "POST"); if (!result.IsSuccess) { return(result); } else { var newToken = JsonConvert.DeserializeObject <Token>(result.Data.ToString()); //建立Cookie double LoginExpireMinute = Convert.ToDouble(_config["LoginExpireMinute"]); var Remove_access_token = new ResultModel(); Remove_access_token = _cookieHelper.Remove("access_token"); var Remove_refresh_token = new ResultModel(); Remove_refresh_token = _cookieHelper.Remove("refresh_token"); if (Remove_access_token.IsSuccess == false || Remove_refresh_token.IsSuccess == false) { result.IsSuccess = false; result.Message = "Delete cookies fail."; return(result); } _cookieHelper.Remove("refresh_token"); CookieOptions cookieOptions = new CookieOptions(); cookieOptions.Expires = new DateTimeOffset(DateTime.Now.AddMinutes(LoginExpireMinute)); var Set_access_token = new ResultModel(); Set_access_token = _cookieHelper.Set("access_token", newToken.access_token, cookieOptions); var Set_refresh_token = new ResultModel(); Set_refresh_token = _cookieHelper.Set("refresh_token", newToken.refresh_token, cookieOptions); if (!Set_access_token.IsSuccess || !Set_refresh_token.IsSuccess) { throw new Exception("Write cookies error."); } } } } catch (Exception e) { result.Message = e.Message; } return(result); }