public async Task <AuthenticationResultModel> GenerateJwtByRefreshToken(string token) { var user = _context.Users.SingleOrDefault(u => u.RefreshTokens.Any(t => t.Token == token)); if (user == null) { return(AuthenticationResultModel.Failed($"Token did not match any users.")); } var refreshToken = user.RefreshTokens.Single(x => x.Token == token); if (!refreshToken.IsActive) { return(AuthenticationResultModel.Failed($"Token Not Active.")); } //Revoke Current Refresh Token refreshToken.Revoked = DateTime.UtcNow; //Generate new Refresh Token and save to Database var newRefreshToken = RefreshTokenGenerator.CreateRefreshToken(); user.RefreshTokens.Add(newRefreshToken); _context.Update(user); _context.SaveChanges(); return(await GetAuthenticationResultModel(user, newRefreshToken)); }
public async Task <AuthenticationResultModel> GenerateJwtByUserPass(AuthenticationRequestModel model) { var user = await _userManager.FindByEmailAsync(model.Email); if (user == null) { return(AuthenticationResultModel.Failed($"No Accounts Registered with {model.Email}.")); } if (await _userManager.CheckPasswordAsync(user, model.Password)) { var refreshToken = new RefreshToken(); if (user.RefreshTokens.Any(a => a.IsActive)) { refreshToken = user.RefreshTokens.FirstOrDefault(a => a.IsActive); } else { refreshToken = RefreshTokenGenerator.CreateRefreshToken(); user.RefreshTokens.Add(refreshToken); _context.Update(user); _context.SaveChanges(); } return(await GetAuthenticationResultModel(user, refreshToken)); } return(AuthenticationResultModel.Failed("Incorrect Credentials for user {user.Email}.")); }