Пример #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);
        }
Пример #2
0
        public static Task OnAuthenticationFailed(AuthenticationFailedContext context)
        {
            var logger = GetLogger(context.HttpContext.RequestServices);

            AuthenticationLogMessages.AuthenticationFailureHandling(logger);

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

            context.Response.Cookies.Delete(options.TokenHeaderAndPayloadCookieKey);
            AuthenticationLogMessages.AuthenticationTokenHeaderAndPayloadDetached(logger, options.TokenSignatureCookieKey);
            context.Response.Cookies.Delete(options.TokenSignatureCookieKey);
            AuthenticationLogMessages.AuthenticationTokenSignatureDetached(logger, options.TokenSignatureCookieKey);

            AuthenticationLogMessages.AuthenticationFailureHandled(logger);
            return(Task.CompletedTask);
        }
Пример #3
0
        public static async Task OnCreatingTicket(OAuthCreatingTicketContext context)
        {
            var logger = GetLogger(context.HttpContext.RequestServices);

            AuthenticationLogMessages.AuthenticationTicketCreationHandling(logger);

            var userId = ulong.Parse(context.Identity.Claims
                                     .First(x => x.Type == ClaimTypes.NameIdentifier)
                                     .Value);

            var ticket = await context.HttpContext.RequestServices
                         .GetRequiredService <IAuthenticationService>()
                         .OnSignInAsync(
                userId: userId,
                username: context.Identity.Claims
                .First(x => x.Type == ClaimTypes.Name)
                .Value,
                discriminator: context.Identity.Claims
                .First(x => x.Type == ApiAuthenticationDefaults.DiscriminatorClaimType)
                .Value,
                avatarHash: context.Identity.Claims
                .First(x => x.Type == ApiAuthenticationDefaults.AvatarHashClaimType)
                .Value,
                getGuildIdsDelegate: cancellationToken => GetGuildIds(context, cancellationToken),
                context.HttpContext.RequestAborted);

            if (ticket is null)
            {
                AuthenticationLogMessages.AuthenticationTicketNotIssued(logger, userId);
                return;
            }
            AuthenticationLogMessages.AuthenticationTicketCreated(logger, ticket);

            context.Identity.AddClaim(new Claim(
                                          ApiAuthenticationDefaults.TicketIdClaimType,
                                          ticket.Id.ToString(),
                                          ClaimValueTypes.Integer64));
            AuthenticationLogMessages.AuthenticationTicketIdClaimAdded(logger, ticket.Id);

            context.Identity.AddClaim(new Claim(
                                          ApiAuthenticationDefaults.PermissionsClaimType,
                                          JsonConvert.SerializeObject(ticket.GrantedPermissions, _jsonSerializerSettings),
                                          JsonClaimValueTypes.Json));
            AuthenticationLogMessages.GrantedPermissionsClaimAdded(logger, ticket.GrantedPermissions);

            AuthenticationLogMessages.AuthenticationTicketCreationHandled(logger);
        }
        public JwtSecurityToken BuildToken(ClaimsIdentity identity)
        {
            var expires = _systemClock.UtcNow.UtcDateTime + _options.Value.TokenLifetime;

            AuthenticationLogMessages.AuthenticationTokenBuilding(_logger, identity, expires);
            var descriptor = new SecurityTokenDescriptor()
            {
                Subject            = identity,
                SigningCredentials = _signingCredentials,
                Expires            = expires
            };

            var token = _tokenHandler.CreateJwtSecurityToken(descriptor);

            AuthenticationLogMessages.AuthenticationTokenBuilt(_logger, token);

            return(token);
        }
Пример #5
0
        protected override Task HandleSignOutAsync(AuthenticationProperties properties)
        {
            AuthenticationLogMessages.SignOutHandling(Logger);

            Response.Cookies.Delete(Options.TokenHeaderAndPayloadCookieKey);
            AuthenticationLogMessages.AuthenticationTokenHeaderAndPayloadDetached(Logger, Options.TokenSignatureCookieKey);
            Response.Cookies.Delete(Options.TokenSignatureCookieKey);
            AuthenticationLogMessages.AuthenticationTokenSignatureDetached(Logger, Options.TokenSignatureCookieKey);

            if (properties.RedirectUri is string)
            {
                AuthenticationLogMessages.IssuingSignOutRedirect(Logger, properties.RedirectUri);
                Response.Redirect(properties.RedirectUri);
            }

            AuthenticationLogMessages.SignOutHandled(Logger);
            return(Task.CompletedTask);
        }
Пример #6
0
        public static Task OnMessageReceived(MessageReceivedContext context)
        {
            var logger = GetLogger(context.HttpContext.RequestServices);

            AuthenticationLogMessages.HttpMessageReceiptHandling(logger);

            var options = context.HttpContext.RequestServices.GetRequiredService <IOptions <ApiAuthenticationOptions> >().Value;
            var cookies = context.Request.Cookies;

            if (cookies.TryGetValue(options.TokenHeaderAndPayloadCookieKey, out var tokenHeaderAndPayload) &&
                cookies.TryGetValue(options.TokenSignatureCookieKey, out var tokenSignature))
            {
                context.Token = $"{tokenHeaderAndPayload}.{tokenSignature}";
                AuthenticationLogMessages.AuthenticationTokenExtracted(logger, context.Token);
            }
            AuthenticationLogMessages.AuthenticationTokenNotFound(logger, options.TokenHeaderAndPayloadCookieKey, options.TokenSignatureCookieKey);

            AuthenticationLogMessages.HttpMessageReceiptHandled(logger);
            return(Task.CompletedTask);
        }
Пример #7
0
        protected override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
        {
            AuthenticationLogMessages.SignInHandling(Logger);

            var token = _apiAuthenticationTokenBuilder.BuildToken(user.Identities.First());

            AuthenticationLogMessages.AuthenticationTokenBuilt(Logger, token);

            var tokenRawHeaderAndPayload = $"{token.RawHeader}.{token.RawPayload}";

            Response.Cookies.Append(
                key: Options.TokenHeaderAndPayloadCookieKey,
                value: tokenRawHeaderAndPayload,
                options: new CookieOptions()
            {
                IsEssential = true,
                SameSite    = SameSiteMode.Strict,
                HttpOnly    = false,
                Secure      = true,
                Expires     = token.ValidTo
            });
            AuthenticationLogMessages.AuthenticationTokenHeaderAndPayloadAttached(Logger, Options.TokenHeaderAndPayloadCookieKey, tokenRawHeaderAndPayload);

            Response.Cookies.Append(
                key: Options.TokenSignatureCookieKey,
                value: token.RawSignature,
                options: new CookieOptions()
            {
                IsEssential = true,
                SameSite    = SameSiteMode.Strict,
                HttpOnly    = true,
                Secure      = true,
                Expires     = token.ValidTo
            });
            AuthenticationLogMessages.AuthenticationTokenSignatureAttached(Logger, Options.TokenSignatureCookieKey, token.RawSignature);

            AuthenticationLogMessages.SignInHandled(Logger);
            return(Task.CompletedTask);
        }