Exemple #1
0
        private async Task AttachUserToContext(HttpContext context, CurrentUserAccessor currentUserAccessor, string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key          = Encoding.ASCII.GetBytes(Secret);
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);

                var jwtToken = (JwtSecurityToken)validatedToken;
                Logger.LogInformation($"Token: {token}");
                foreach (var claim in jwtToken.Claims)
                {
                    Logger.LogInformation($"{claim.Type} - {claim.Value} ");
                }
                var userId = jwtToken.Claims.First(x => x.Type == "unique_name").Value;
                Logger.LogInformation($"Current user: {userId}");

                context.User = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim>()
                {
                    new(ClaimTypes.NameIdentifier, userId),
                    new(ClaimTypes.Name, userId)
                }));
            }
Exemple #2
0
        public async Task Invoke(HttpContext context, CurrentUserAccessor currentUserAccessor)
        {
            var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();

            if (token != null)
            {
                await AttachUserToContext(context, currentUserAccessor, token);
            }

            await Next(context);
        }