A little backstory, I'm playing around with .Net Core, it's OAuth and Cookie implimentations to do a database/identity-free auth system.
So far, I've been able to create a custom OAuth Middleware component and hook it up with the CookieAuthentication Middleware.
I then had some issues ensuring that the access_token was not being purged after it's expiration, the CookieMiddleware would continue to keep a user logged in until the cookie expired and never check to see if the access_token was still valid.
To solve this, I was able to create and inject an event into the CookieAuthenticationOptions which would, on every request, test the expiration of the access_token and sign the user out if it was expired:
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme, LoginPath = new PathString("/Auth/EveSSOLogin"), AutomaticChallenge = true, SlidingExpiration =false, Events = new CookieAuthenticationEvents { OnValidatePrincipal = EveSSOClientValidator.ValidateAsync }
});
public static async Task ValidateAsync(CookieValidatePrincipalContext context) { DateTime expires = DateTime.MinValue; var tokens = context.Properties.GetTokens(); var accessToken = tokens.FirstOrDefault(t => t.Name.Equals("access_token", StringComparison.OrdinalIgnoreCase))?.Value; var expiresString = tokens.FirstOrDefault(t => t.Name.Equals("expires_at", StringComparison.OrdinalIgnoreCase))?.Value; if (string.IsNullOrWhiteSpace(expiresString) || !DateTime.TryParse(expiresString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out expires) || DateTime.UtcNow > expires.ToUniversalTime()) { context.RejectPrincipal(); await context.HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } }
The issue I'm having now, is that I need to handle refresh tokens. Surprisingly, there doesn't appear to be any built-in support to handle refresh tokens. Does Identity handle this? So I've been looking around for a decent place to intercept the request and perform the process of refreshing the token and saving the new token data, if it fails, then let it proceed with the re-authorization.
To do this, I need access to the ClientId, ClientSecret and the refresh_token, all at the same time. But the CookieAuthentication middleware contains the refresh_token and my OAuthAuthentication middleware contains both ClientId and ClientSecret, and I have yet to find a place where these two meet.
So that's where I'm stuck now and after being at this for the better part of a day, I am asking for help. Even pointing me to the right area in the source code would be beneficial as I almost feel like I've memorized everything to do with Microsoft.AspNetCore.Authentication and Microsoft.AspNetCore.Authentication.OAuth.
Just in case you want punish yourself by viewing bad code, you can see the full project here (word of warning, it's messier than normal because I've been testing various things).