Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override the OpenIdConnectAuthenticationHandler RememberNonce Method

I have an issue that seems well documented using Office 365 authentication where the cookie becomes too large for the headers as multiple nonce messages are stored.

I have found the following code but I can't get it to fire on authentication so can someone help with what I am missing:

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);
    }
}
like image 374
Steve Borman Avatar asked Oct 29 '22 08:10

Steve Borman


1 Answers

Create a class that inherits from OpenIdConnectAuthenticationMiddleware class that returns the handler in the CreateHandler method.

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);
    }
}

Then add the middleware into the OWIN runtime.

For example:

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);
}
like image 161
Jannes Avatar answered Jan 02 '23 21:01

Jannes