public IActionResult Login(string returnUrl, LogInModel model) { if (!ModelState.IsValid) { return(View(model)); } UserProfile findUser = _userService.LogIn(model, out string resultCode); if (findUser == null) { ModelState.AddModelError("LoginError", _localizer[resultCode].Value); return(View(model)); } // 要存的資訊: 看要存字串還是json var claims = new List <Claim>() { new Claim(ClaimTypes.Name, findUser.USER_NO), new Claim(ClaimTypes.NameIdentifier, findUser.USER_NO), new Claim(ClaimTypes.MobilePhone, findUser.PHONE ?? "") }; var roles = findUser.Roles .Select(r => new Claim(ClaimTypes.Role, LogicCenter.GetEnumName(r.ROLE_ID))); var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); identity.AddClaims(claims); identity.AddClaims(roles); // 製作身分驗證Cookie var principal = new ClaimsPrincipal(identity); if (model.RememberMe) { HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true }); } else { // 過期時間 var timeSpanOffset = DateTimeOffset.UtcNow.AddMinutes(30); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true, ExpiresUtc = timeSpanOffset }); } return(Redirect(returnUrl ?? Url.Action("Index", "Home"))); }
public IActionResult Login(string returnUrl, LogInModel model) { UserProfile findUser = _userService.LogIn(model, out string resultCode); if (findUser == null) { return(Ok(model)); } // 要存的資訊 var claims = new List <Claim>() { new Claim(ClaimTypes.Name, findUser.USER_NO), new Claim(ClaimTypes.NameIdentifier, findUser.USER_NO), new Claim(ClaimTypes.MobilePhone, findUser.PHONE ?? "") }; var roles = findUser.Roles .Select(r => new Claim(ClaimTypes.Role, LogicCenter.GetEnumName(r.ROLE_ID))); claims.AddRange(roles); // Json Web Token 登入 var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken ( issuer: Configuration["Tokens:ValidIssuer"], audience: Configuration["Tokens:ValidAudience"], claims: claims, expires: DateTime.UtcNow.AddHours(1), /* 過期時間 */ signingCredentials: new SigningCredentials(new SymmetricSecurityKey (System.Text.Encoding.UTF8.GetBytes(Configuration["Tokens:IssuerSigningKey"])), SecurityAlgorithms.HmacSha256) ); string tokenString = new JwtSecurityTokenHandler().WriteToken(token); return(Ok( new { user = findUser, token = tokenString })); }