Rest 在控制器上使用Authorize属性时返回自定义响应

Rest 在控制器上使用Authorize属性时返回自定义响应,rest,.net-core,asp.net-core-webapi,bearer-token,authorize-attribute,Rest,.net Core,Asp.net Core Webapi,Bearer Token,Authorize Attribute,我刚刚实现了承载令牌,并将Authorize属性添加到我的控制器类中,效果很好。看起来是这样的: [授权(AuthenticationSchemes=JwtBearerDefaults.AuthenticationScheme)] 我想做的是在服务器出现故障时创建一个更复杂的响应,而不是标准的401 我尝试了过滤器,但根本没有调用它们 有什么办法吗 拥有自定义方案、自定义授权处理程序和poof 请注意,我在ConfigureServices中注入了处理程序: services.AddAuthen

我刚刚实现了承载令牌,并将Authorize属性添加到我的控制器类中,效果很好。看起来是这样的:

[授权(AuthenticationSchemes=JwtBearerDefaults.AuthenticationScheme)]

我想做的是在服务器出现故障时创建一个更复杂的响应,而不是标准的401

我尝试了过滤器,但根本没有调用它们


有什么办法吗

拥有自定义方案、自定义授权处理程序和poof

请注意,我在ConfigureServices中注入了处理程序:

services.AddAuthentication(options =>
            {
                options.DefaultScheme = ApiKeyAuthenticationOptions.DefaultScheme;
                options.DefaultAuthenticateScheme = ApiKeyAuthenticationOptions.DefaultScheme;
            })
                .AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(
                    ApiKeyAuthenticationOptions.DefaultScheme, o => { });
ApiKeyAuthenticationHandler

//
///用于通过Api密钥处理.NET核心项目身份验证的身份验证处理程序。
///
///这有助于解决使用非传统方法时的依赖性问题。
/// https://stackoverflow.com/questions/47324129/no-authenticationscheme-was-specified-and-there-was-no-defaultchallengescheme-f
/// 
公共类ApiKeyAuthenticationHandler:AuthenticationHandler

public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions
    {
        public const string DefaultScheme = "API Key";
        public string Scheme => DefaultScheme;
        public string AuthenticationType = DefaultScheme;
        public const string HeaderKey = "X-Api-Key";
    }
    /// <summary>
    /// An Auth handler to handle authentication for a .NET Core project via Api keys.
    ///
    /// This helps to resolve dependency issues when utilises a non-conventional method.
    /// https://stackoverflow.com/questions/47324129/no-authenticationscheme-was-specified-and-there-was-no-defaultchallengescheme-f
    /// </summary>
    public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
    {
        private readonly IServiceProvider _serviceProvider;

        public ApiKeyAuthenticationHandler(IOptionsMonitor<ApiKeyAuthenticationOptions> options, ILoggerFactory logger, 
            UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider) 
            : base (options, logger, encoder, clock) 
        {
            _serviceProvider = serviceProvider;
        }

        protected override Task<AuthenticateResult> HandleAuthenticateAsync() 
        {
            var token = Request.Headers[ApiKeyAuthenticationOptions.HeaderKey];

            if (string.IsNullOrEmpty(token)) {
                return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
            }

            var customRedisEvent = _serviceProvider.GetRequiredService<ICustomRedisEvent>();
            var isValidToken = customRedisEvent.Exists(token, RedisDatabases.ApiKeyUser);

            if (!isValidToken) {
                return Task.FromResult (AuthenticateResult.Fail ($"Invalid token {token}."));
            }

            var claims = new [] { new Claim ("token", token) };
            var identity = new ClaimsIdentity (claims, nameof (ApiKeyAuthenticationHandler));
            var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), Scheme.Name);
            return Task.FromResult (AuthenticateResult.Success (ticket));
        }
    }