Esempio n. 1
0
        private async Task AttachUserToContext(HttpContext context, IUserContract userService, string token)
        {
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

            token = token.Replace("Bearer ", string.Empty);
            tokenHandler.ValidateToken(token, new TokenValidationParameters
            {
                ValidateIssuer           = false,
                ValidateAudience         = false,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.Secret))
            }, out SecurityToken validatedToken);

            JwtSecurityToken jwtToken = tokenHandler.ReadJwtToken(token);

            //attach user to context on successful jwt validation
            long    UserId  = long.Parse(jwtToken.Claims.First(x => x.Type == "UserId").Value);
            UserDto userDto = await userService.GetById(UserId);

            if (userDto == null)
            {
                throw new AccessViolationException();
            }
            context.Items["UserId"] = userDto.UserId;
        }