private static async Task AuthorizationCodeReceived(AuthorizationCodeReceivedNotification n, string authority, string clientId, string clientSecret) { var tokenEndpoint = $"{authority}/connect/token"; if (n.Code != null) { // use the code to get the access and refresh token var tokenResponse = await StsTokenHelper.RequestToken(_client, tokenEndpoint, clientId, clientSecret, n.Code, n.RedirectUri); // create new identity //var claimsIdent = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType); var claimsIdent = n.AuthenticationTicket.Identity; bool includeUserClaims = claimsIdent.FindFirst("role") == null; if (includeUserClaims) { //Add userClaims from userInfoEndpoint with the access token await AddUserClaimsAsync(claimsIdent, authority, tokenResponse.AccessToken); //Add portal //AddPortalGroupInfo(claimsIdent); } claimsIdent.AddOrUpdateClaim("access_token", tokenResponse.AccessToken); claimsIdent.AddOrUpdateClaim("expires_at", tokenResponse.ExpiresUtc().ToString()); claimsIdent.AddOrUpdateClaim("refresh_token", tokenResponse.RefreshToken); claimsIdent.AddOrUpdateClaim("id_token", n.ProtocolMessage.IdToken); n.AuthenticationTicket.Properties.ExpiresUtc = tokenResponse.ExpiresUtc(); } }
private static async Task ValidateAccessToken(CookieValidateIdentityContext ctx, string tokenEndpoint, string clientId, string clientSecret) { var claimsIdentity = ctx?.Identity; if (claimsIdentity == null) { return; } DateTimeOffset expiresAt; DateTimeOffset.TryParse(claimsIdentity.FindFirst("expires_at")?.Value, out expiresAt); try { //Check for expired token if (DateTimeOffset.UtcNow.AddMinutes(5) >= expiresAt) { Trace.WriteLine($"Token expiring, expiresAt: {expiresAt}, now: {DateTimeOffset.UtcNow}"); string refreshToken = claimsIdentity.FindFirst("refresh_token")?.Value; if (refreshToken == null) { Trace.WriteLine("No refresh token, rejecting identity"); ctx.RejectIdentity(); return; } var tokenResponse = await StsTokenHelper.RefreshToken(_client, tokenEndpoint, clientId, clientSecret, refreshToken); if (tokenResponse.IsError) { Trace.WriteLine("RefreshToken resulted in error, rejecting identity"); ctx.RejectIdentity(); return; } claimsIdentity.AddOrUpdateClaim("access_token", tokenResponse.AccessToken); claimsIdentity.AddOrUpdateClaim("expires_at", tokenResponse.ExpiresUtc().ToString()); claimsIdentity.AddOrUpdateClaim("refresh_token", tokenResponse.RefreshToken); //ctx.ReplaceIdentity(claimsIdentity); // kill old cookie ctx.OwinContext.Authentication.SignOut(ctx.Options.AuthenticationType); // sign in again var authenticationProperties = new AuthenticationProperties { IsPersistent = ctx.Properties.IsPersistent }; ctx.OwinContext.Authentication.SignIn(authenticationProperties, claimsIdentity); } } catch (Exception ex) { Trace.WriteLine($"Exception occurred, rejecting identity\r\n{ex.Message}\r\n{ex.StackTrace}"); ctx.RejectIdentity(); } }