private async Task <IActionResult> RefreshToekn(GenerateJwtViewModel model) { var client = await _authClientRepo.GetAsync(model.client_id); if (client == null) { // should be Unauthorized return(BadRequestWithErrors("invalid_client", "client_id")); } if (client.ApplicationType != ApplicationType.JavaScript && client.Secret != model.client_secret) // we should compare with hash, in future { return(BadRequestWithErrors("invalid_secret", "client_secret")); } var token = await _authRefreshTokenRepo.GetTokenAsync(model.refresh_token, model.client_id); if (token == null || client == null) { return(BadRequestWithErrors("can_not_refresh_token")); } if (!token.IsActive) { return(BadRequestWithErrors("refresh_token_has_expired")); } var refresh_token = Guid.NewGuid().ToString("n"); token.IsActive = false; //expire the old refresh_token and add a new refresh_token var updateFlag = _authRefreshTokenRepo.ExpireToken(token); var addFlag = _authRefreshTokenRepo.AddToken(new AuthRefreshToken(model.client_id, token.Subject, refresh_token, DateTime.UtcNow.AddMinutes(client.RefreshTokenLifeTime))); var user = await _userMgr.FindByNameAsync(model.username); if (user != null && updateFlag && addFlag) { return(Ok(await GetJwt(model.client_id, client.RefreshTokenLifeTime, refresh_token, null))); } return(BadRequest()); }
public async Task <IActionResult> CreateToken([FromBody] GenerateJwtViewModel model) { if (model == null) { return(BadRequest()); } if (model.grant_type == "password") { return(await GenerateToken(model)); } else if (model.grant_type == "refresh_token") { return(await RefreshToekn(model)); } else { return(BadRequestWithErrors("invalid_grant_type", "grant_type")); } }
private async Task <IActionResult> GenerateToken(GenerateJwtViewModel model) { var client = await _authClientRepo.GetAsync(model.client_id); if (client == null) { return(BadRequestWithErrors("invalid_client", "client_id")); } if (client.ApplicationType != ApplicationType.JavaScript && client.Secret != model.client_secret) // we should compare with hash, in future { return(BadRequestWithErrors("invalid_secret", "client_secret")); } var user = await _userMgr.FindByNameAsync(model.username); if (user == null) { return(BadRequestWithErrors("user_not_found!", "username")); } if (user != null && string.IsNullOrEmpty(model.password) || _hasher.VerifyHashedPassword(user, user.PasswordHash, model.password) == PasswordVerificationResult.Success) { var refreshTokenKey = Guid.NewGuid().ToString("n"); var refreshToken = new AuthRefreshToken(model.client_id, model.username, refreshTokenKey, DateTime.UtcNow.AddMinutes(client.RefreshTokenLifeTime)); if (_authRefreshTokenRepo.AddToken(refreshToken)) { return(Ok(await GetJwt(model.client_id, client.RefreshTokenLifeTime, refreshTokenKey, user))); } else { return(BadRequestWithErrors("can_not_add_token_to_database")); } } return(BadRequestWithErrors("wrong_password!", "password")); }