I am trying to build the ASP.NET Core Web API from this link (https://docs.microsoft.com/en-us/azure/notification-hubs/push-notifications-android-specific-users-firebase-cloud-messaging). It wants me to register the MessageHandler using the following code:
config.MessageHandlers.Add(new AuthenticationTestHandler());
It says to "add the following code at the end of the Register method in the Program.cs file. There is no register method in the Program.cs file. Everything I have found indicates that the Register method is part of a class called WebApiConfig
, but I don't have one of those either, and when I create one, it cannot find HttpConfiguration. How do I register the MessageHandler?
CodePudding user response:
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://docs.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