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