Invoke(Microsoft.AspNetCore.Http.HttpContext context, Application.Services.IUserService userService) { var requestHeaders = context.Request.Headers["Authorization"]; var token = requestHeaders .FirstOrDefault() ?.Split(" ") .Last(); if (token != null) { JwtUtility.AttachUserToContext(context: context, userService: userService, token: token, secretKey: MainSettings.SecretKey); } await Next(context); }
public static void AttachUserToContext (Microsoft.AspNetCore.Http.HttpContext context, Application.Services.IUserService userService, string token, string secretKey) { try { var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler(); var key = System.Text.Encoding.ASCII.GetBytes(secretKey); tokenHandler.ValidateToken(token: token, validationParameters: new Microsoft.IdentityModel.Tokens.TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateIssuerSigningKey = true, IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key), // Set clockskew to zero so tokens expire // exactly at token expiration time (instead of 5 minutes later) ClockSkew = System.TimeSpan.Zero }, out Microsoft.IdentityModel.Tokens.SecurityToken validatedToken); var jwtToken = validatedToken as System.IdentityModel.Tokens.Jwt.JwtSecurityToken; System.Security.Claims.Claim userIdClaim = jwtToken.Claims .Where(current => current.Type.ToLower() == "NameId".ToLower()) .FirstOrDefault(); // دقت کنید که دستور ذیل کار نمیکند //.Where(current => current.Type == System.Security.Claims.ClaimTypes.NameIdentifier) if (userIdClaim == null) { return; } var userId = int.Parse(userIdClaim.Value); Models.User foundedUser = userService.GetById(userId); if (foundedUser == null) { return; } // Attach user to context on successful jwt validation context.Items["User"] = foundedUser; } catch // (System.Exception ex) { // Log ex //string errorMessage = ex.Message; // Do nothing if jwt validation fails // user is not attached to context so request won't have access to secure routes } }