Search code examples
c#asp.netowinkatana

Using OnValidateIdentity to perform additional validation on cookie data


On Brock Allen's blog, he states that

the CookieAuthenticationOptions class has a Provider property ... and it has properties which are delegates you can subscribe to. This allows you to validate the cookie as it comes into the application (OnValidateIdentity). In this callback you can reject or replace the identity.

I'm new to OWIN and C#, so am struggling to adapt the many examples of OnValidateIdentity that I've found online to suit my needs. After the cookie has been accepted as valid on each 'private' web page, I'd like to check for the following things:

  1. The cookie contains at least one claim
  2. The CustomerId claim value is greater than zero

I can achieve these two checks in a normal method, but I can't figure out how to hook the login into OnValidateIdentity. Here's what I have so far:

I've written some code, but can't figure out what needs to be returned from the method used.

public void Configuration(IAppBuilder app)
{
    dynamic cookieExpirationPeriod = TimeSpan.FromMinutes(60);

    CookieAuthenticationProvider prov = new CookieAuthenticationProvider();
    prov.OnValidateIdentity = ctx =>
    {
        MyClaimsIdentityObject si = MyApp.Identity.Current();
        if (si == null || si.UserId == 0 || si.CustomerId == 0) {
            ctx.RejectIdentity();
            // what needs to happen here for a return value?
        }
    };


    CookieAuthenticationOptions coa = new CookieAuthenticationOptions {
        AuthenticationMode = AuthenticationMode.Active,
        CookieName = "MyApp",
        ExpireTimeSpan = cookieExpirationPeriod,
        SlidingExpiration = true,
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/login.aspx"),
        CookieHttpOnly = true,
        Provider = prov
    };

    if (HttpContext.Current.Request.IsLocal) {
        coa.CookieSecure = CookieSecureOption.Never;
    } else {
        coa.CookieSecure = CookieSecureOption.Always;
    }

    app.UseCookieAuthentication(coa);

}

Solution

  • I believe that is just:

    return Task.FromResult<int>(0);