Search code examples
c#asp.net-coreauthenticationasp.net-identityminimal-apis

How do I add authentication to an ASP.NET Core minimal API using Identity, but without using Azure?


I'm sure the answer to this must be obvious, as it's an obvious thing want to do, but I can't seem to find any guidance.

I have an ASP.NET Core minimal API, and want to add authentication. I already have Identity set up in a different project, and want to use the same database (ie the same users) for the API.

I saw this blog post, which looked promising until I realised that the code there checks the user name and password as plain text (using admin as both in the sample)...

if (credentials[0] == "admin" && credentials[1] == "admin")

The problem with this is that (thankfully), Identity does not store the passwords in plain text, they are hashed, so I can't do a simple comparison.

I tried hashing the incoming password, as shown in this answer, but that didn't work as the hash came out different every time I called _userManager.PasswordHasher.HashPassword.

I tried using the ASP.NET Core's SignInManager.CanSignInAsync method to check if I could sign in with the credentials, but that required me to add the following to Program...

builder.Services.AddIdentity<User, IdentityRole>(options => {
    // options removed for clarity
  })
  .AddDefaultTokenProviders()
  .AddEntityFrameworkStores<AppDbContext>();

However, as soon as I did this, any request to the API attempted to redirect to a log-in page, which is obviously not going to work when the API is being called from code.

All I could find on Microsoft's site was this article, but that assumes you are using Azure. At the moment, I'm still developing this on my local machine, and I don't know yet whether the project owners want to deploy to Azure or their own hosted server, so the code there doesn't help me.

Anyone able to explain to me how I do what seems like such an obvious and simple task? Please let me know if there is any more info I need to provide. Thanks


Solution

  • Have you seen Bipin Joshi's series of articles on this subject? My guess is that you are past the first few, but you might find these useful...

    Implement JWT Authentication In ASP.NET Core Minimal APIs

    Integrate ASP.NET Core Identity With JWT And Minimal APIs

    The one change I made when using that approach was that the getToken API call just takes two string parameters for the user name and password, instead of a User object. Given that it's only two parameters, I find this makes life easier when working with disparate projects, as you don't need the class definition. Up to you though.

    In order to call the API, you'll need to call getToken first, passing in the user name and password. Once you have your token, you can then set the authentication on your HtpClient as follows...

    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);