Basic Auth for .NET Core

Utilising Basic Auth with .NET Core Identity

Updated: 03 September 2023

.NET Core Identity using Local Users can be used natively on application endpoints, this however makes use of a few additional layers of abstracting which can make using it with a WebAPI kind of troublesome

In order to add your own custom authentication which makes use of Basic Auth and the UserManager Dependency provided by Identity, you can do the following

In your API Class, define the following private property

1
public class ApiController : ControllerBase
2
{
3
private readonly UserManager<IdentityUser> _userManager;

Next, in your Controller’s constructor you need to add the UserManager dependency

1
public ApiController(UserManager<IdentityUser> userManager)
2
{
3
_userManager = userManager;
4
}

In your application class, you can then provide a function which will verify the user login based on the HttpContext of the request, however this can also be implemented as a free-standing function which takes the username, password, and Usermanager as inputs and works purely by making use of those. But for this context this function is defined inside of the controller class. This will return a bool which indicates if the user making the request has been authenticated

1
private async Task<bool> isUserAuthenticted()
2
{
3
var passwordHasher = new PasswordHasher<IdentityUser>();
4
5
string authHeader = HttpContext.Request.Headers["Authorization"];
6
7
if (authHeader != null && authHeader.StartsWith("Basic"))
8
{
9
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
10
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
11
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
12
13
int seperatorIndex = usernamePassword.IndexOf(':');
14
15
var username = usernamePassword.Substring(0, seperatorIndex);
16
var password = usernamePassword.Substring(seperatorIndex + 1);
17
18
var user = await _userManager.FindByNameAsync(username);
19
20
var verificationResult = await _userManager.CheckPasswordAsync(user, password);
21
22
return verificationResult;
23
}
24
else
25
{
26
return false;
27
}
28
}

The above can then be implemented by a controller with something like:

1
public async Task<ActionResult<string>> GetText()
2
{
3
if (await isUserAuthenticated)
4
{
5
return "Hello world";
6
}
7
else
8
{
9
return Unauthorized();
10
}
11
}