Skip to content
This repository has been archived by the owner on Apr 28, 2023. It is now read-only.

Nisden/HMAC

Repository files navigation

HMAC Authentication

Simple HMAC authentication for ASP.NET Core

  1. Create your own class that implements ISecretLookup.
        public class ApplicationSecretLookup : ISecretLookup
        {
            private readonly ApplicationDbContext context;            

            public ApplicationSecretLookup(ApplicationDbContext context) 
            {
                this.context = context
            }

            public async Task<byte[]> LookupAsync(string id)
            {
                return (await context.Secrets.SingleOrDefaultAsync(x => x.Id == id)).SharedSecret;
            }
        }
  1. Modify your Startup.cs
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "HMAC";
            }).AddHMACAuthentication();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("AuthenticationRequired", policy =>
                {
                    policy.RequireAuthenticatedUser();
                });
            });

            services.AddScoped<ISecretLookup, ApplicationSecretLookup>();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication();
        }
  1. Use the SignatureHelper to help generate an valid signature.
// Calculate Signature
string authenticationSignature = SignatureHelper.Calculate(TestStartup.Secret, SignatureHelper.Generate(requestMessage.Headers.Date.Value, requestMessage?.Content?.Headers.ContentLength ?? 0, requestMessage.Method.Method, "/HelloWorld", ""));
requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("HMAC", TestStartup.Id + ":" + authenticationSignature);

HMAC

The following values are used for generating the signature

  • Date
  • Content-Length
  • Method
  • Path
  • Query

Nuget

Build status

Package feed: https://ci.appveyor.com/nuget/hmac-8ur3ps4toqs6

About

HMAC Authentication for ASP.NET Core

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages