In ASP.NET Core the equivalent to a MessageHandler is middleware. I converted AuthenticationTestHandler to middleware:
AuthenticationTestMiddleware.cs:
public class AuthenticationTestMiddleware
{
private readonly RequestDelegate _next;
public AuthenticationTestMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var authorizationHeader = context.Request.Headers["Authorization"].FirstOrDefault();
if (authorizationHeader != null && authorizationHeader
.StartsWith("Basic ", StringComparison.InvariantCultureIgnoreCase))
{
string authorizationUserAndPwdBase64 =
authorizationHeader.Substring("Basic ".Length);
string authorizationUserAndPwd = Encoding.Default
.GetString(Convert.FromBase64String(authorizationUserAndPwdBase64));
string user = authorizationUserAndPwd.Split(':')[0];
string password = authorizationUserAndPwd.Split(':')[1];
if (VerifyUserAndPwd(user, password))
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user)
};
var claimsIdentity = new ClaimsIdentity(
claims: claims,
authenticationType: "password");
context.User.AddIdentity(claimsIdentity);
await _next(context);
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
}
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
}
}
private bool VerifyUserAndPwd(string user, string password)
{
// This is not a real authentication scheme.
return user == password;
}
}
Now in Program.cs you can register like this:
app.UseMiddleware<AuthenticationTestMiddleware>();
Questions I found regarding converting MessageHandler to middleware:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-6.0
Edit:
Found an official sample that is updated for ASP.NET Core:
https://github.com/Azure/azure-notificationhubs-dotnet/tree/main/Samples/WebApiSample/WebApiSample