public IActionResult Authenticate(string username, string password) { var user = UserMock.FindUser(username, password); if (user == null) { return(Unauthorized()); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(Consts.Secret); var authTime = DateTime.UtcNow; var expiresAt = authTime.AddDays(7); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(JwtClaimTypes.Audience, "api"), new Claim(JwtClaimTypes.Issuer, "http://localhost:5200"), new Claim(JwtClaimTypes.Id, user.Id.ToString()), new Claim(JwtClaimTypes.Name, user.Name), new Claim(JwtClaimTypes.Email, user.Email), new Claim(JwtClaimTypes.PhoneNumber, user.PhoneNumber) }), Expires = expiresAt, SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); return(Ok(new { access_token = tokenString, token_type = "Bearer", profile = new { sid = user.Id, name = user.Name, auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(), expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds() } })); }
public IActionResult GetToken(string username, string password) { string accessToken = _cache.Get <string>(username); if (!(accessToken?.Length > 0)) { UserModel user = UserMock.FindUser(username, password); Dictionary <string, object> keyValuePairs = new Dictionary <string, object>(); keyValuePairs.Add(nameof(user.Id), user.Id); keyValuePairs.Add(nameof(user.UserName), user.UserName); keyValuePairs.Add(nameof(user.Phone), user.Phone); keyValuePairs.Add(nameof(user.Email), user.Email); accessToken = _tokenContext.GetToken(keyValuePairs, 120); _cache.Set(user.UserName, accessToken, DateTime.Now.AddHours(2)); } return(Json(new { access_token = accessToken })); }
public IActionResult Login(string username, string password, string ReturnUrl = "") { CurrentUser user = UserMock.FindUser(username, password);//这里写自己的认证逻辑 var claimIdentity = new ClaimsIdentity("Cookie"); claimIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())); claimIdentity.AddClaim(new Claim(ClaimTypes.Name, user.Name)); claimIdentity.AddClaim(new Claim(ClaimTypes.Email, user.Email)); claimIdentity.AddClaim(new Claim(ClaimTypes.Role, user.Role)); var claimsPrincipal = new ClaimsPrincipal(claimIdentity); // 在Startup注册AddAuthentication时,指定了默认的Scheme,在这里便可以不再指定Scheme。 base.HttpContext.SignInAsync(claimsPrincipal).Wait(); //SignInAsync 登入 if (!string.IsNullOrEmpty(ReturnUrl)) { return(Redirect(ReturnUrl)); } return(Redirect("~/Home/Index")); }