protected async override Task <AuthenticateResult> HandleAuthenticateAsync() { var header = SplitAuthenticationHeader(); if (header == null) { return(AuthenticateResult.NoResult()); } // Verify that request data is within acceptable time if (!DateTimeOffset.TryParseExact(Request.Headers[DateHeader], "r", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal, out DateTimeOffset requestDate)) { return(AuthenticateResult.Fail("Unable to parse Date header")); } if (requestDate > Clock.UtcNow.Add(Options.AllowedDateDrift) || requestDate < Clock.UtcNow.Subtract(Options.AllowedDateDrift)) { return(AuthenticateResult.Fail("Date is drifted more than allowed, adjust your time settings.")); } // Lookup and verify secret Logger.LogDebug("Looking up secret for {Id}", header.Value.id); var secret = await lookup.LookupAsync(header.Value.id); if (secret == null) { Logger.LogInformation("No secret found for {Id}", header.Value.id); return(AuthenticateResult.Fail("Invalid id")); } else if (secret.Length != 32) { Logger.LogError("Secret must be 32 bytes in size"); throw new InvalidOperationException("Incorrect secret size"); } // Check signature string serverSignature = SignatureHelper.Calculate(secret, SignatureHelper.Generate(requestDate, Request.ContentLength ?? 0, Request.Method, Request.Path, Request.QueryString.Value)); Logger.LogDebug("Calculated server side signature {signature}", serverSignature); if (serverSignature.Equals(header.Value.signature)) { return(AuthenticateResult.Success(new AuthenticationTicket( new GenericPrincipal(new GenericIdentity(header.Value.id), Options.GetRolesForId?.Invoke(header.Value.id) ?? null), new AuthenticationProperties() { IsPersistent = false, AllowRefresh = false }, Options.Schema))); } else { return(AuthenticateResult.Fail("Invalid signature")); } }
public async Task <ResponseResult <string> > GetEcho(string echo, string apiId) { var endpoint = _configuration.Settings.Endpoints.FirstOrDefault(x => x.ApiId == apiId); if (endpoint == null) { Console.WriteLine($"Failed to load Endpoint {apiId}"); throw new Exception($"Failed to load Endpoint {apiId}"); } // Create request var requestUri = $"{endpoint.Url}/{echo}"; var requestMessage = new HttpRequestMessage(HttpMethod.Get, requestUri); requestMessage.Headers.Date = DateTimeOffset.UtcNow; // Calculate Signature string authenticationSignature = SignatureHelper.Calculate( endpoint.ApiKey, SignatureHelper.Generate( requestMessage.Headers.Date.Value, requestMessage?.Content?.Headers.ContentLength ?? 0, requestMessage.Method.Method, requestMessage.RequestUri.PathAndQuery, "")); requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue( endpoint.Scheme, endpoint.ApiId + ":" + authenticationSignature); // Send request var httpResponseMessage = await _client.SendAsync(requestMessage); if (httpResponseMessage.IsSuccessStatusCode) { string responseString = await httpResponseMessage.Content.ReadAsStringAsync(); Console.WriteLine(responseString); Console.WriteLine("GET - HTTP Status: {0}, Reason {1}", httpResponseMessage.StatusCode, httpResponseMessage.ReasonPhrase); return(JsonSerializer.Deserialize <ResponseResult <string> >(responseString)); } else { Console.WriteLine("Failed to call the API. HTTP Status: {0}, Reason {1}", httpResponseMessage.StatusCode, httpResponseMessage.ReasonPhrase); return(null); } }
public async Task PostWrongCredentials(string key, string secret) { string payload = "test"; var request = new HttpRequestMessage(new HttpMethod("POST"), new Uri(client.BaseAddress, "/queue")); request.Content = new StringContent(payload); request.Headers.Date = DateTimeOffset.UtcNow; var nonce = Guid.NewGuid().ToString(); request.Headers.Add("Nonce", nonce); string authenticationSignature = SignatureHelper.Calculate(secret, SignatureHelper.Generate(request.Headers.Date.Value, payload, request.Method.Method, request.RequestUri.AbsolutePath, request.RequestUri.Query, nonce)); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("HMAC", $"{key}:{authenticationSignature}"); using var response = await client.SendAsync(request, CancellationToken.None); Assert.AreEqual(System.Net.HttpStatusCode.Unauthorized, response.StatusCode); }
public async Task PostNotJson() { string payload = "test"; var request = new HttpRequestMessage(new HttpMethod("POST"), new Uri(client.BaseAddress, "/queue")); request.Content = new StringContent(payload); request.Headers.Date = DateTimeOffset.UtcNow; var nonce = Guid.NewGuid().ToString(); request.Headers.Add("Nonce", nonce); string authenticationSignature = SignatureHelper.Calculate("devhmacsecret", SignatureHelper.Generate(request.Headers.Date.Value, payload, request.Method.Method, request.RequestUri.AbsolutePath, request.RequestUri.Query, nonce)); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("HMAC", "DevQueueService:" + authenticationSignature); using var response = await client.SendAsync(request, CancellationToken.None); Assert.AreEqual(System.Net.HttpStatusCode.UnsupportedMediaType, response.StatusCode); }
public async Task PostExecuteWorkerNotExists() { string payload = System.Text.Json.JsonSerializer.Serialize(new EnqueueRequest { Payload = "test", QueueName = "test" }); var request = new HttpRequestMessage(new HttpMethod("POST"), new Uri(client.BaseAddress, "/queue")) { Content = new StringContent(payload, Encoding.UTF8, "application/json") }; request.Headers.Date = DateTimeOffset.UtcNow; var nonce = Guid.NewGuid().ToString(); request.Headers.Add("Nonce", nonce); string authenticationSignature = SignatureHelper.Calculate("devhmacsecret", SignatureHelper.Generate(request.Headers.Date.Value, payload, request.Method.Method, request.RequestUri.AbsolutePath, request.RequestUri.Query, nonce)); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("HMAC", "DevQueueService:" + authenticationSignature); using var response = await client.SendAsync(request, CancellationToken.None); Assert.AreEqual(System.Net.HttpStatusCode.InternalServerError, response.StatusCode); }
public async Task CanAuthenticateUsingPostAndQueryAndWithoutCustomMessageHandler() { // Create request var requestMessage = new HttpRequestMessage(HttpMethod.Post, "/HelloWorld?Something=Lol"); requestMessage.Headers.Date = DateTimeOffset.UtcNow; requestMessage.Content = new StringContent("Beeb boob duup"); // Calculate Signature string authenticationSignature = SignatureHelper.Calculate(TestStartup.Secret, SignatureHelper.Generate(requestMessage.Headers.Date.Value, requestMessage?.Content?.Headers.ContentLength ?? 0, requestMessage.Method.Method, "/HelloWorld", "Something=Lol")); requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("HMAC", TestStartup.Id + ":" + authenticationSignature); // Send request var result = await _client.SendAsync(requestMessage); Assert.Equal(200, (int)result.StatusCode); Assert.Equal("Hello World!", await result.Content.ReadAsStringAsync()); }