|
| 1 | +using Microsoft.AspNetCore.Mvc; |
| 2 | +using Microsoft.AspNetCore.Mvc.Filters; |
| 3 | +using Microsoft.Extensions.DependencyInjection; |
| 4 | +using Microsoft.Extensions.Options; |
| 5 | +using System; |
| 6 | +using System.IO; |
| 7 | +using System.Linq; |
| 8 | +using System.Security.Cryptography; |
| 9 | +using System.Text; |
| 10 | +using System.Threading.Tasks; |
| 11 | +using Umbraco.Cms.Integrations.OAuthProxy.Configuration; |
| 12 | + |
| 13 | +namespace Umbraco.Cms.Integrations.OAuthProxy.Filters |
| 14 | +{ |
| 15 | + public class SignatureValidationAttribute : ActionFilterAttribute |
| 16 | + { |
| 17 | + private const string HeaderKey = "X-Shopify-Hmac-Sha256"; |
| 18 | + |
| 19 | + public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) |
| 20 | + { |
| 21 | + var appSettings = context.HttpContext.RequestServices.GetService<IOptions<AppSettings>>().Value; |
| 22 | + |
| 23 | + var hmacHeaderValues = context.HttpContext.Request.Headers |
| 24 | + .FirstOrDefault(kvp => kvp.Key.Equals(HeaderKey, StringComparison.OrdinalIgnoreCase)).Value; |
| 25 | + |
| 26 | + if (hmacHeaderValues.Count == 0) |
| 27 | + { |
| 28 | + context.Result = new UnauthorizedResult(); |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + string hmacHeader = hmacHeaderValues.First(); |
| 33 | + |
| 34 | + HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(appSettings.ShopifyClientSecret)); |
| 35 | + |
| 36 | + var bodyStream = new StreamReader(context.HttpContext.Request.Body); |
| 37 | + string requestBody = await bodyStream.ReadToEndAsync(); |
| 38 | + string hash = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(requestBody))); |
| 39 | + |
| 40 | + if (hash != hmacHeader) |
| 41 | + { |
| 42 | + context.Result = new UnauthorizedResult(); |
| 43 | + return; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | +} |
0 commit comments