/// <summary> /// Generates refresh token and persists it to database /// </summary> /// <param name="user">User for whom a token is generated</param> /// <returns>Refresh token</returns> private async Task <AuthToken> GenerateRefreshToken(User user) { //TODO think about hashing and persistence security var refreshToken = new RefreshToken { Id = CryptographicHelpers.GetHash(Guid.NewGuid().ToString()), ClientApp = "", ValidFrom = DateTime.UtcNow, ValidTo = DateTime.UtcNow.Add(TimeSpan.FromMinutes(_authenticationOptions.RefreshTokenLifetime)), UserId = user.Id }; var refreshTokenRepository = UnitOfWork.Repository <RefreshToken>(); refreshTokenRepository.RemoveRange(refreshTokenRepository.GetAll().Where(x => x.UserId == user.Id)); refreshTokenRepository.Add(refreshToken); await UnitOfWork.SaveChangesAsync(); return(new AuthToken { Issuer = _authenticationOptions.Issuer, ValidTo = refreshToken.ValidTo, Token = refreshToken.Id }); }
protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { HttpResponseMessage response = null; string requestContentBase64String = string.Empty; string requestUri = System.Net.WebUtility.UrlEncode(request.RequestUri.AbsoluteUri).ToLower(); string requestHttpMethod = request.Method.Method; //Calculate UNIX time DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc); TimeSpan timeSpan = DateTime.UtcNow - epochStart; string requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString(); //create random nonce for each request string nonce = Guid.NewGuid().ToString("N"); //Checking if the request contains body, usually will be null wiht HTTP GET and DELETE if (request.Content != null) { requestContentBase64String = CryptographicHelpers.MD5Hash(request.Content.ReadAsStringAsync().Result); } //Creating the raw signature string string signatureRawData = String.Format("{0}{1}{2}{3}{4}{5}", APPId, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String); var requestSignatureBase64String = CryptographicHelpers.HmacSha256(APIKey, signatureRawData); request.Headers.Authorization = new AuthenticationHeaderValue("amx", string.Format("{0}:{1}:{2}:{3}", APPId, requestSignatureBase64String, nonce, requestTimeStamp)); response = await base.SendAsync(request, cancellationToken); return(response); }