예제 #1
0
        private async Task AttachUserToContext(HttpContext context, ICurrentUserAccessor 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}");

                // attach user to context on successful jwt validation
                context.Items["User"] = await currentUserAccessor.FindById(userId);
            }
            catch (Exception e) {
                Logger.LogWarning($"Error: no user found: {e.Message}");
                // do nothing if jwt validation fails
                // user is not attached to context so request won't have access to secure routes
            }
        }