I have two types of authentication in my project, the first is through JWT and the second will still be implemented.
In case of error with JWT authentication I need to call the second type of authentication, and in case of success, proceed with the call to controller.
However, the handling of the OnAuthenticationFailed event does not work.
How to force a success inside the OnAuthenticationFailed event?
It does not work
services.AddAuthentication(BearerAuthenticationDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = configuration.GetSection("AuthenticationConfiguration").GetValue<string>("Authority");
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateAudience = false
};
options.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
//here a second authentication will be implemented
//(if secondauthentication.IsSucess)
c.Exception = null;
c.Success();
return Task.CompletedTask;
}
};
});
The Asp.net application can have multiple authentication services. Instead of writing the second type of authentication in the authentication failed event of first one, register it as an authentication middleware is recommend.
For example, the following code registers authentication services and handlers for cookie and JWT bearer authentication schemes:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => Configuration.Bind("JwtSettings", options))
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => Configuration.Bind("CookieSettings", options));
More details about authentication, you can refer to the document below: