Example #1
0
        public static async Task OnTokenValidated(TokenValidatedContext context)
        {
            var logger = GetLogger(context.HttpContext.RequestServices);

            AuthenticationLogMessages.AuthenticationTokenValidationHandling(logger, context.SecurityToken);

            var jwtSecurityToken = (JwtSecurityToken)context.SecurityToken;

            var ticketId = (long)jwtSecurityToken.Payload[ApiAuthenticationDefaults.TicketIdClaimType];

            AuthenticationLogMessages.AuthenticationPerforming(logger, ticketId);
            var ticket = await context.HttpContext.RequestServices
                         .GetRequiredService <IAuthenticationService>()
                         .OnAuthenticatedAsync(
                ticketId: ticketId,
                userId: ((string)jwtSecurityToken.Payload["nameid"])
                .ParseUInt64(),
                username: (string)jwtSecurityToken.Payload["unique_name"],
                discriminator: (string)jwtSecurityToken.Payload[ApiAuthenticationDefaults.DiscriminatorClaimType],
                avatarHash: (string)jwtSecurityToken.Payload[ApiAuthenticationDefaults.AvatarHashClaimType],
                grantedPermissions: ((JObject)jwtSecurityToken.Payload[ApiAuthenticationDefaults.PermissionsClaimType])
                .ToObject <Dictionary <int, string> >(),
                context.HttpContext.RequestAborted);

            AuthenticationLogMessages.AuthenticationPerformed(logger, ticket);

            var renewSignIn = ticket.Id != ticketId;

            if (!renewSignIn)
            {
                AuthenticationLogMessages.AuthenticationTokenExpirationValidating(logger, jwtSecurityToken.ValidFrom);

                var options = context.HttpContext.RequestServices.GetRequiredService <IOptions <ApiAuthenticationOptions> >().Value;
                var now     = context.HttpContext.RequestServices.GetRequiredService <ISystemClock>().UtcNow;

                renewSignIn = (now - jwtSecurityToken.ValidFrom) > options.TokenRefreshInterval;
            }

            if (renewSignIn)
            {
                AuthenticationLogMessages.AuthenticationTokenRenewing(logger);

                var identity = context.Principal.Identities.First();
                identity.RemoveClaim(identity.FindFirst(ApiAuthenticationDefaults.TicketIdClaimType));
                identity.AddClaim(new Claim(
                                      ApiAuthenticationDefaults.TicketIdClaimType,
                                      ticket.Id.ToString(),
                                      ClaimValueTypes.Integer64));

                await context.HttpContext.SignInAsync(ApiAuthenticationDefaults.AuthenticationScheme, context.Principal);

                AuthenticationLogMessages.AuthenticationTokenRenewed(logger);
            }

            AuthenticationLogMessages.AuthenticationTokenValidationHandled(logger);
        }