private async Task <IAccount> TryCookieAuthenticationAsync(IOwinEnvironment context, IClient client) { string[] rawCookies = null; if (!context.Request.Headers.TryGetValue("Cookie", out rawCookies)) { logger.Trace("No cookie header found", nameof(TryCookieAuthenticationAsync)); return(null); } var cookieParser = new CookieParser(rawCookies, logger); if (cookieParser.Count == 0) { logger.Trace("No cookies parsed from header", nameof(TryCookieAuthenticationAsync)); return(null); } logger.Trace("Cookies found on request: " + cookieParser.AsEnumerable().Select(x => $"'{x.Key}'").Join(", "), nameof(TryCookieAuthenticationAsync)); var accessToken = cookieParser.Get(this.Configuration.Web.AccessTokenCookie.Name); var refreshToken = cookieParser.Get(this.Configuration.Web.RefreshTokenCookie.Name); // Attempt to validate incoming Access Token if (!string.IsNullOrEmpty(accessToken)) { logger.Trace($"Found nonempty access token cookie '{this.Configuration.Web.AccessTokenCookie.Name}'", nameof(TryCookieAuthenticationAsync)); var validAccount = await ValidateAccessTokenAsync(context, client, accessToken); if (validAccount != null) { logger.Info("Request authenticated using Access Token cookie", nameof(TryCookieAuthenticationAsync)); return(validAccount); } else { logger.Info("Access token cookie was not valid", nameof(TryCookieAuthenticationAsync)); } } // Try using refresh token instead if (!string.IsNullOrEmpty(refreshToken)) { logger.Trace($"Found nonempty refresh token cookie '{this.Configuration.Web.RefreshTokenCookie.Name}'", nameof(TryCookieAuthenticationAsync)); var refreshedAccount = await RefreshAccessTokenAsync(context, client, refreshToken); if (refreshedAccount != null) { logger.Info("Request authenticated using Refresh Token cookie", nameof(TryCookieAuthenticationAsync)); return(refreshedAccount); } else { logger.Info("Refresh token cookie was not valid", nameof(TryCookieAuthenticationAsync)); } } // Failed on both counts. Delete access and refresh token cookies if necessary if (cookieParser.Contains(this.Configuration.Web.AccessTokenCookie.Name)) { Cookies.DeleteTokenCookie(context, this.Configuration.Web.AccessTokenCookie, logger); } if (cookieParser.Contains(this.Configuration.Web.RefreshTokenCookie.Name)) { Cookies.DeleteTokenCookie(context, this.Configuration.Web.RefreshTokenCookie, logger); } logger.Info("No access or refresh token cookies found", nameof(TryCookieAuthenticationAsync)); return(null); }