如何覆盖OpenIdConnectAuthenticationHandler RememberNonce方法

时间:2017-04-25 07:58:29

标签: openid-connect

我有一个问题似乎是使用Office 365身份验证记录得很好的,因为存储多个nonce消息时,cookie对于标头来说太大了。

我找到了以下代码,但我无法启动身份验证,因此有人可以帮助解决我所缺少的问题:

public class SawtoothOpenIdConnectAuthenticationHandler:OpenIdConnectAuthenticationHandler     {         public SawtoothOpenIdConnectAuthenticationHandler(ILogger logger)             :base(logger){}

    protected override void RememberNonce(OpenIdConnectMessage message, string nonce)
    {
        var oldNonces = Request.Cookies.Where(kvp => kvp.Key.StartsWith(OpenIdConnectAuthenticationDefaults.CookiePrefix + "nonce"));
        if (oldNonces.Any())
        {
            CookieOptions cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = Request.IsSecure
            };
            foreach (KeyValuePair<string, string> oldNonce in oldNonces)
            {
                Response.Cookies.Delete(oldNonce.Key, cookieOptions);
            }
        }
        base.RememberNonce(message, nonce);
    }
}

1 个答案:

答案 0 :(得分:1)

创建一个从OpenIdConnectAuthenticationMiddleware类继承的类,该类返回CreateHandler方法中的处理程序。

public class SawtoothOpenIdConnectAuthenticationMiddleware : OpenIdConnectAuthenticationMiddleware
{
    private readonly ILogger _logger;

    public SawtoothOpenIdConnectAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, OpenIdConnectAuthenticationOptions options) : base(next, app, options)
    {
        _logger = app.CreateLogger<SawtoothOpenIdConnectAuthenticationMiddleware>();
    }

    protected override AuthenticationHandler<OpenIdConnectAuthenticationOptions> CreateHandler()
    {
        return new SawtoothOpenIdConnectAuthenticationHandler(_logger);
    }
}

然后将中间件添加到OWIN运行时中。

例如:

public static IAppBuilder UseSawtoothOpenIdConnectAuthentication(this IAppBuilder app, OpenIdConnectAuthenticationOptions openIdConnectOptions)
{
    if (app == null)
    {
        throw new ArgumentNullException("app");
    }

    if (openIdConnectOptions == null)
    {
        throw new ArgumentNullException("openIdConnectOptions");
    }

    return app.Use(typeof(SawtoothOpenIdConnectAuthenticationMiddleware), app, openIdConnectOptions);
}