I was trying to return the custom error response message, when Unauthorized
request is made to api. I have tried several event handler to alter the responses, but none of them seems to work in my case.
What is the proper openiddict
event handler to alter the responses when there is unauthorized request?
What i have tried so far.
public class CustomAuthorizationHandler : IOpenIddictServerEventHandler<OpenIddictServerEvents.ApplyTokenResponse>
{
public Task HandleAsync(OpenIddictServerEvents.ApplyTokenResponse notification, CancellationToken cancellationToken)
{
}
}
public class CustomAuthorizationResponseHandler : IOpenIddictServerEventHandler<OpenIddictServerEvents.ApplyAuthorizationResponse>
{
public Task HandleAsync(OpenIddictServerEvents.ApplyAuthorizationResponse notification, CancellationToken cancellationToken)
{
}
}
public class CustomValidateAuthorizationRequestHandler : IOpenIddictServerEventHandler<OpenIddictServerEvents.HandleAuthorizationRequest>
{
public Task HandleAsync(OpenIddictServerEvents.HandleAuthorizationRequest notification, CancellationToken cancellationToken)
{
}
}
Add Server in Startup.cs
services.AddOpenIddict().AddCore(options =>
{
options.UseEntityFrameworkCore()
.UseDbContext<AWSContext>()
.ReplaceDefaultEntities<Guid>();
}).AddServer(options =>
{
options.UseMvc();
options.EnableAuthorizationEndpoint("/connect/authorize")
.EnableTokenEndpoint("/connect/token")
.EnableLogoutEndpoint("/connect/logout")
.EnableIntrospectionEndpoint("/connect/introspect")
.EnableUserinfoEndpoint("/api/userinfo");
options.AllowClientCredentialsFlow();
options.RegisterScopes(OpenIdConnectConstants.Scopes.Email,
OpenIdConnectConstants.Scopes.Profile,
OpenIddictConstants.Scopes.Roles);
options.AddEphemeralSigningKey();
options.AllowImplicitFlow();
options.DisableHttpsRequirement();
options.AddEventHandler<OpenIddictServerEvents.ApplyTokenResponse, CustomAuthorizationHandler>();
options.AddEventHandler<OpenIddictServerEvents.ApplyAuthorizationResponse, CustomAuthorizationResponseHandler>();
options.AddEventHandler<OpenIddictServerEvents.HandleAuthorizationRequest, CustomValidateAuthorizationRequestHandler>();
//options.AddDevelopmentSigningCertificate();
options.UseJsonWebTokens();
});//.AddValidation();
Controller
[HttpGet("~/home/message")]
[Authorize(AuthenticationSchemes = OpenIddictValidationDefaults.AuthenticationScheme)]
public async Task<IActionResult> GetMessage()
{
var subject = User.FindFirst(OpenIdConnectConstants.Claims.Subject)?.Value;
if (string.IsNullOrEmpty(subject))
{
return BadRequest();
}
var application = await _applicationManager.FindByClientIdAsync(subject, HttpContext.RequestAborted);
if (application == null)
{
return BadRequest();
}
return Content($"{application.DisplayName} has been successfully authenticated.");
}
Postman getting 401 error: