在未授权用户的自定义身份验证中显示 AuthenticateResult.Fail("Invalid Token Used for Authorisation" )

Display AuthenticateResult.Fail("Invalid Token Used for Authorisation" ) in custom Authentication for unauthorised user

这是自定义身份验证的 class,但它不会为错误的令牌密钥打印消息(令牌密钥是每个用户的唯一字符串) =>AuthenticateResult.Fail("Invalid Token Used for Authorisation") 它只是在 postman 中显示 Unauthorized 401 状态码。
var valtoken = auth.getTokenDetails(令牌);方法 returns 用户详细信息,如果具有指定令牌的用户可以访问控制器的 get 方法,否则 returns null。因此,对于空结果,我想 return Unauthorized 401 status code with custom message for Get api call

namespace CustomAuthDemo
{
/*public class AuthenticationSchemeConstants
{
    public const string BasicAuthScheme = "Basic";
}*/
public class BasicAuthSchemeOptions:AuthenticationSchemeOptions
{

}
public class CustAuthHandler : AuthenticationHandler<BasicAuthSchemeOptions>
{
    private readonly ICustomAuthService auth;
    public CustAuthHandler(IOptionsMonitor<BasicAuthSchemeOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock,
        ICustomAuthService auth):base(options,logger,encoder,clock)
        {
        this.auth = auth;
        }
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.ContainsKey("Authorization"))
            return AuthenticateResult.Fail("Unauthorised");

        string authheader = Request.Headers["Authorization"];
        if (string.IsNullOrEmpty(authheader))
            return AuthenticateResult.Fail("Unauthorised");

        if(!authheader.StartsWith("bearer",StringComparison.OrdinalIgnoreCase))
            return AuthenticateResult.Fail("Unauthorised");

        string token = authheader.Substring("bearer".Length).Trim();
        try
        {
            return ValidateToken(token);
        }
        catch(Exception ex)
        {
            Logger.LogInformation(ex.Message);
            return AuthenticateResult.Fail("Unauthorised");
        }
    }
    private AuthenticateResult ValidateToken(string token)
    {
        if (string.IsNullOrEmpty(token))
            return AuthenticateResult.Fail("Unauthorised");
        var valtoken = auth.getTokenDetails(token);
        if (valtoken == null)
            return AuthenticateResult.Fail("Invalid Token Used for Authorisation");
        var claims = new List<Claim>
        { new Claim(ClaimTypes.Name,valtoken.username)};

        var identity = new ClaimsIdentity(claims, Scheme.Name);
        var principal = new GenericPrincipal(identity, null);
        var ticket = new AuthenticationTicket(principal, Scheme.Name);
        return AuthenticateResult.Success(ticket);
    }

我只是重写了 CustAuthHandler 中的 HandleChallengeAsync 方法,当授权失败时,这个方法被称为 Eveytime,所以我写回了一个字符串和 401 状态代码到我的 http 请求的响应体中,它没有通过身份验证。

protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            
            await base.HandleChallengeAsync(properties);
            Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            string output = "authentification failed you don't have access to this content";
            await Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(output));
        
           
        }