适当的事件处理程序,用于在未经授权的情况下更改响应

问题描述 投票:0回答:1

当我向api提出Unauthorized请求时,我试图返回自定义错误响应消息。我尝试了几种事件处理程序来更改响应,但是在我看来,它们似乎都不起作用。

什么是适当的openiddict事件处理程序,用于在未经授权的情况下更改响应?

到目前为止我尝试过的。

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)
    {

    }

}

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.");
}

邮递员收到401错误:

enter image description here

asp.net-core openid-connect openiddict
1个回答
0
投票

仅是代码示例,如果使用AddJwtBearer自定义错误作为响应:

services.AddAuthentication("myschema")
.AddJwtBearer("myschema", options =>
{
    options.Authority = "http://localhost:54540/";
    options.Audience = "resource_server";
    options.RequireHttpsMetadata = false;
    options.Events = new JwtBearerEvents();

    options.Events.OnChallenge = context =>
    {
        // Skip the default logic.
        context.HandleResponse();
        if (string.IsNullOrEmpty(context.HttpContext.Request.Headers["Authorization"]))
        {
            var payload = new JObject
            {
                ["error"] = "No token",
                ["error_description"] = "No token",
            };
            return context.Response.WriteAsync(payload.ToString());
        }

        else
        {
            var payload = new JObject
            {
                ["error"] = context.Error,
                ["error_description"] = context.ErrorDescription,
                ["error_uri"] = context.ErrorUri
            };
            return context.Response.WriteAsync(payload.ToString());
        }

    };
});

并采取行动:

[Authorize(AuthenticationSchemes = "myschema")]
[HttpGet("message")]
public async Task<IActionResult> GetMessage()
{
    var user = await _userManager.GetUserAsync(User);
    if (user == null)
    {
        return BadRequest();
    }

    return Content($"{user.UserName} has been successfully authenticated.");
}
© www.soinside.com 2019 - 2024. All rights reserved.