private void AttachUserToContext(HttpContext context, IUserAuthService userService, string accessToken, string refreshToken) { try { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); tokenHandler.ValidateToken(accessToken, 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; var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value); // attach user to context on successful jwt validation context.Items["User"] = userService.GetById(userId); } catch { try { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); tokenHandler.ValidateToken(refreshToken, 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; var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value); // attach user to context on successful jwt validation context.Items["User"] = userService.GetById(userId); } catch { // do nothing if jwt validation fails // user is not attached to context so request won't have access to secure routes } } }
public IResult UserIdExists(int id) { var userAuth = _userAuthService.GetById(id); if (userAuth != null) { return(new SuccessResult("Kullanıcı mevcut")); } return(new ErrorResult("Kullanıcı bulunamadı.")); }
public IActionResult GetById(int userAuthId) { var result = _userAuthService.GetById(userAuthId); if (result.Success) { return(Ok(result)); } return(BadRequest(result)); }