在Owin中间件中设置挑战

本文关键字:设置 挑战 中间件 Owin | 更新日期: 2023-09-27 18:02:51

自己的中间件实现在添加挑战之前查找自己的身份验证类型,因此只有适当的中间件响应。多重挑战可以同时使用

protected override Task ApplyResponseChallengeAsync()
{
    if (Response.StatusCode == 401)
    {
        var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
        if (challenge != null)
        {
            Response.Headers.AppendValues("WWW-Authenticate", _challenge);
        }
    }
    return Task.FromResult<object>(null);
}

当使用内置的Cookie或Bearer中间件时,"Bearer"类型总是存在并被查找。

我要在哪里添加我自己的挑战类型全局,所以它被查找?这可以在请求上下文中通过调用

手动完成。
Request.GetOwinContext().Authentication.Challenge("Basic");

但是我想为所有的控制器添加一个全局配置

在Owin中间件中设置挑战

可以使用AuthenticationManager.Challenge()的方法设置AuthenticationResponseChallenge。例如,在你的startup.cs中,你可以有像context.Authentication.Challenge(new AuthenticationProperties(), Options.AuthenticationType)这样的东西,这样中间件就对应于Options。AuthenticationType在查找。

时返回此挑战。

活动中间件将尝试处理所有传出的挑战,而不考虑其AuthenticationType。通常,只有cookie中间件被设置为活动状态,其他所有中间件都是被动状态。对于被动中间件,要对质询进行操作,质询应该具有匹配的AuthenticationType。