Skip to content

Instantly share code, notes, and snippets.

@alanta
Created February 6, 2023 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alanta/033ac8bb25aaf76737b338a7c31798e3 to your computer and use it in GitHub Desktop.
Save alanta/033ac8bb25aaf76737b338a7c31798e3 to your computer and use it in GitHub Desktop.
Add HMAC support to Swagger
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;
public static void AddSwaggerHMACSupport(this IServiceCollection services)
{
const string HmacSecretHeaderName = "X-HMAC-Secret";
services.Configure<SwaggerUIOptions>(opts =>
{
// Pull in crypto-js to handle request hashing
opts.InjectJavascript("https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js");
// Request handler to
// - pull the secret out of the specified header and remove that header from the request
// - Set the request timestamp in a header
// - Sign the request using HMAC
opts.UseRequestInterceptor(
@"(req) => { if(req.url.endsWith('swagger.json')) return req; var now = Date.now(); req.headers['X-Request-Timestamp'] = now; var secret = req.headers['"+ HmacSecretHeaderName+"']; delete req.headers['"+ HmacSecretHeaderName+"']; var payload=req.method.toUpperCase()+req.url+now+req.body; var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secret); hmac.update(payload); req.headers['X-Request-Signature'] = CryptoJS.enc.Base64.stringify(hmac.finalize()); return req; }");
});
services.Configure<SwaggerGenOptions>(options =>
{
options.AddSecurityDefinition("HMAC",
new OpenApiSecurityScheme
{
Description = "HMAC request signing",
Type = SecuritySchemeType.ApiKey,
Name = HmacSecretHeaderName, // this header is removed by the request interceptor.
In = ParameterLocation.Header
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "HMAC" }
},
new string[] { }
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment