private static bool IsRequestFresh(HmacAuthenticationParameter parameter, out Tuple <ParseResult <Instant>, Instant, Duration> freshnessIndicators) { var now = NodaTime.SystemClock.Instance.GetCurrentInstant(); var parseResult = InstantPattern.General.Parse(parameter.Time); if (!parseResult.Success) { freshnessIndicators = Tuple.Create(parseResult, now, Duration.MaxValue); return(false); } var offset = now - parseResult.Value; if (offset < Duration.Zero) { offset = Duration.Negate(offset); } var isRequestFresh = offset < Duration.FromMinutes(15); freshnessIndicators = Tuple.Create(parseResult, now, offset); return(isRequestFresh); }
private static bool TryGetHmacAuthenticationParameter( ILogger logger, IPAddress remoteIPAddress, string authorizationHeaderValue, out HmacAuthenticationParameter parameter) { var headerValues = authorizationHeaderValue.Split( new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); if (headerValues.Length != 2 || headerValues[0] != HmacSchemeName) { parameter = null; return(false); } try { parameter = headerValues[1].ConvertFromJson <HmacAuthenticationParameter>();; return(true); } catch (Exception ex) { logger?.LogWarning( ex, "Bad HMAC authentication header from IP {RemoteIPAddress}: {AuthorizationHeaderValue}", remoteIPAddress.ToJson(), authorizationHeaderValue); parameter = null; return(false); } }
public static string Generate( HmacAuthenticationParameter parameter, Guid secretKey, string endpointUri, string jsonContent = null) { if (endpointUri == null) { throw new ArgumentNullException(nameof(endpointUri)); } if (endpointUri == string.Empty) { throw new ArgumentException("Cannot be empty", nameof(endpointUri)); } // normalize any URL encoded characters endpointUri = WebUtility.UrlDecode(endpointUri); // exclude the endpointUri scheme if it exists because reverse proxies will sometimes changing the scheme var slashSlashIndex = endpointUri.IndexOf("//"); if (slashSlashIndex >= 0) { endpointUri = endpointUri.Substring(slashSlashIndex + 1); } var parameterContainer = new { EndpointUri = endpointUri, JsonContent = jsonContent ?? string.Empty, Parameter = parameter.CloneWithoutHash(), }; using (var generator = new HMACSHA512 { Key = secretKey.ToByteArray() }) { return(Convert.ToBase64String( generator.ComputeHash( Encoding.UTF8.GetBytes(parameterContainer.ToJson())))); } }
public AuthenticationHeaderValue GenerateAuthenticationHeader( string endpointUri, string jsonContent = null) { var parameter = new HmacAuthenticationParameter { ApplicationKey = this.ApplicationSecrets.ApplicationKey, AuthenticatedUser = this.UserLookup.GetAuthenticatedUser(), Time = InstantPattern.General.Format(this.Clock.GetCurrentInstant()), }; parameter.Hash = HmacHashGenerator.Generate( parameter, this.ApplicationSecrets.ApplicationSecretKey, endpointUri, jsonContent); return(new AuthenticationHeaderValue("hmac", parameter.ToJson())); }