ASP.NET Core-从AuthenticationHandler取回消息 [英] ASP.NET Core - getting a message back from AuthenticationHandler

查看:592
本文介绍了ASP.NET Core-从AuthenticationHandler取回消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了AuthenticationHandler的子类.它返回AuthenticationResult.Fail("This is why you can't log in");

I have implemented a subclass of AuthenticationHandler. It returns AuthenticationResult.Fail("This is why you can't log in");

我希望该消息最终出现在正文中,或者至少出现在HTTP状态文本中,但是我会收到空​​白的401响应.

I would have expected this message to end up in the body, or at least in the HTTP status text, but instead I get a blank 401 response.

有什么方法可以为ASP.NET Core中失败的身份验证尝试提供其他信息吗?

Is there any way to provide additional information for failed authentication attempts in ASP.NET core?

推荐答案

要更改正文或Http状态,可以尝试Context.Response.

For changing the body or Http status, you could try Context.Response.

这是演示代码:

using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace TestIdentity
{
    public class CustomAuthenticationHandler<TOptions> : AuthenticationHandler<TOptions> where TOptions : AuthenticationSchemeOptions, new()
    {
        public CustomAuthenticationHandler(IOptionsMonitor<TOptions> options
            , ILoggerFactory logger
            , UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
        {

        }
        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            await Context.Response.WriteAsync("This is why you can't log in");
            return AuthenticateResult.Fail("This is why you can't log in");
        }
    }
}

这篇关于ASP.NET Core-从AuthenticationHandler取回消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆