public async Task <JwtResult> GenerateToken(HttpRequest request, List <string> CallTrace) { string UserName = request.Form["UserName"]; UserName = UserName.Substring(0, UserName.Length - 10); string UserPass = request.Form["UserPass"]; UserPass = UserPass.Substring(0, UserPass.Length - 10); string UserType = request.Form["UserType"]; UserType = UserType.Substring(0, UserType.Length - 10); WebApiUserTypesEnum tmpWebApiUserType = (WebApiUserTypesEnum)int.Parse(UserType); string MachineID = request.Form["MachineID"]; MachineID = MachineID.Substring(0, MachineID.Length - 10); string Par_Out_Result = string.Empty; string tmp_IPAddress = request.HttpContext.Connection.RemoteIpAddress.ToString(); var identity = await GetIdentity(UserName, UserPass, tmp_IPAddress, MachineID, tmpWebApiUserType, out Par_Out_Result, TodosCosmos.LocalFunctions.AddThisCaller(CallTrace, MethodBase.GetCurrentMethod())); if (identity == null) { JwtResult result = new JwtResult { AccessToken = string.Empty, ExpiresIn = 0, ErrorMessage = Par_Out_Result, }; return(result); } var now = DateTime.UtcNow; var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, "tmp_User"), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, GlobalFunctions.ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64), new Claim("UserID", Par_Out_Result), new Claim("UserName", UserName.ToLower() + GlobalFunctions.GetRandomAlphaNumeric(10)), new Claim("MachineID", request.Form["MachineID"]), new Claim("ClientIP", tmp_IPAddress + GlobalFunctions.GetRandomAlphaNumeric(10)), new Claim("roles", ((int)tmpWebApiUserType).ToString() + GlobalFunctions.GetRandomAlphaNumeric(10)), }; // Create the JWT and write it to a string var jwt = new JwtSecurityToken( issuer: _options.Issuer, audience: _options.Audience, claims: claims, notBefore: now, expires: now.Add(_options.Expiration), signingCredentials: _options.SigningCredentials); try { JwtResult result = new JwtResult { AccessToken = new JwtSecurityTokenHandler().WriteToken(jwt), ExpiresIn = (int)_options.Expiration.TotalSeconds, ErrorMessage = string.Empty }; return(result); } catch (Exception ex) { JwtResult result = new JwtResult { AccessToken = string.Empty, ExpiresIn = 0, ErrorMessage = ex.Message }; return(result); } }
public static ClaimsPrincipal Authenticate(HttpRequest request, List <WebApiUserTypesEnum> AllowedRoles, List <string> CallTrace) { string token = GetTokenFromRequest(request, TodosCosmos.LocalFunctions.AddThisCaller(CallTrace, MethodBase.GetCurrentMethod())); if (string.IsNullOrEmpty(token)) { throw new UnauthorizedAccessException(); } var tokenHandler = new JwtSecurityTokenHandler(); var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken; if (jwtToken == null) { return(null); } var tokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(GlobalData.JWTSecret)), // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = "ExampleIssuer", // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = "ExampleAudience", // Validate the token expiry ValidateLifetime = true, // If you want to allow a certain amount of clock drift, set that here: //ClockSkew = TimeSpan.Zero, }; SecurityToken securityToken; var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken); if (principal == null) { throw new UnauthorizedAccessException(); } if (AllowedRoles.Any()) { WebApiUserTypesEnum UserRole = (WebApiUserTypesEnum)int.Parse(LocalFunctions.CmdGetValueFromRoleClaim(principal.Claims, 10, TodosCosmos.LocalFunctions.AddThisCaller(CallTrace, MethodBase.GetCurrentMethod()))); if (AllowedRoles.Any(x => x.Equals(UserRole))) { return(principal); } else { throw new UnauthorizedAccessException(); } } else { return(principal); } }
private Task <ClaimsIdentity> GetIdentity(string Par_Username, string Par_Password, string Par_IPAddress, string Par_MachineID, WebApiUserTypesEnum ParWebApiUserType, out string Par_Out_Result, List <string> CallTrace) { Par_Out_Result = string.Empty; try { switch (ParWebApiUserType) { case WebApiUserTypesEnum.NotAuthorized: if (Par_Username.Equals(GlobalData.NotAuthorizedUserName) && Par_Password.Equals(GlobalData.NotAuthorizedUserPass)) { Par_Out_Result = Guid.Empty.ToString() + GlobalFunctions.GetRandomAlphaNumeric(10); return(Task.FromResult(new ClaimsIdentity(new System.Security.Principal.GenericIdentity(Par_Username, "Token"), new Claim[] { }))); } else { Par_Out_Result = "Invalid NotAutorizedUser UserName or Password"; } break; case WebApiUserTypesEnum.Authorized: CosmosDocUser cosmosDocUser = CosmosAPI.cosmosDBClientUser.FindUserByUserName(Par_Username, TodosCosmos.LocalFunctions.AddThisCaller(CallTrace, MethodBase.GetCurrentMethod())).Result; if (cosmosDocUser != null) { if (LocalFunctions.CompareHash(Par_Password, cosmosDocUser, TodosCosmos.LocalFunctions.AddThisCaller(CallTrace, MethodBase.GetCurrentMethod()))) { Par_Out_Result = cosmosDocUser.ID.ToString() + GlobalFunctions.GetRandomAlphaNumeric(10); return(Task.FromResult(new ClaimsIdentity(new System.Security.Principal.GenericIdentity(Par_Username, "Token"), new Claim[] { }))); } else { Par_Out_Result = "Invalid User Password"; } } else { Par_Out_Result = "Invalid User Name"; } break; case WebApiUserTypesEnum.Admin: if (Par_IPAddress.Equals(GlobalData.AdminIPAddress)) { if (Par_MachineID.Equals(GlobalData.AdminMachineID)) { if (Par_Username.Equals(GlobalData.AdminUserName) && Par_Password.Equals(GlobalData.AdminUserPass)) { Par_Out_Result = Guid.Empty.ToString() + GlobalFunctions.GetRandomAlphaNumeric(10); return(Task.FromResult(new ClaimsIdentity(new System.Security.Principal.GenericIdentity(Par_Username, "Token"), new Claim[] { }))); } else { Par_Out_Result = "Invalid Admin UserName or Password"; } } else { Par_Out_Result = "Invalid Admin MachineID"; } } else { Par_Out_Result = "Invalid Admin IPAddress"; } break; default: Par_Out_Result = "unknown error"; break; } } catch (Exception ex) { bool b = CosmosAPI.cosmosDBClientError.AddErrorLog(Guid.Empty, ex.Message, TodosCosmos.LocalFunctions.AddThisCaller(CallTrace, MethodBase.GetCurrentMethod())).Result; } return(Task.FromResult <ClaimsIdentity>(null)); }
internal static async Task <JwtResult> CmdDownloadToken(SecureString ParUserName, SecureString ParPassword, WebApiUserTypesEnum ParWebApiUserTypesEnum = WebApiUserTypesEnum.NotAuthorized) { try { httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); string username = GlobalFunctions.ConvertToPlainString(ParUserName); if (string.IsNullOrEmpty(username)) { return(new JwtResult { ErrorMessage = "Username is not provided!" }); } string password = GlobalFunctions.ConvertToPlainString(ParPassword); if (string.IsNullOrEmpty(password)) { return(new JwtResult { ErrorMessage = "Password is not provided!" }); } var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("UserName", username + GlobalFunctions.GetRandomAlphaNumeric()), new KeyValuePair <string, string>("UserPass", password + GlobalFunctions.GetRandomAlphaNumeric()), new KeyValuePair <string, string>("UserType", ((int)ParWebApiUserTypesEnum).ToString() + GlobalFunctions.GetRandomAlphaNumeric()), new KeyValuePair <string, string>("MachineID", LocalData.MachineID + GlobalFunctions.GetRandomAlphaNumeric()), }); return(await httpClient.MyPostFormGetJsonAsync <JwtResult>("token", formContent)); } catch (Exception ex) { LocalFunctions.AddError(ex.Message, MethodBase.GetCurrentMethod(), true, false); return(new JwtResult()); } }
private async Task GenerateToken(HttpContext context) { string UserName = GlobalFunctions.CmdAsymmetricDecrypt(context.Request.Form["UserName"]); UserName = UserName.Substring(0, UserName.Length - 10); string UserPass = GlobalFunctions.CmdAsymmetricDecrypt(context.Request.Form["UserPass"]); UserPass = UserPass.Substring(0, UserPass.Length - 10); string UserType = GlobalFunctions.CmdAsymmetricDecrypt(context.Request.Form["UserType"]); UserType = UserType.Substring(0, UserType.Length - 10); WebApiUserTypesEnum tmpWebApiUserType = (WebApiUserTypesEnum)Convert.ToInt16(UserType); string MachineID = GlobalFunctions.CmdAsymmetricDecrypt(context.Request.Form["MachineID"]); MachineID = MachineID.Substring(0, MachineID.Length - 10); string Par_Out_Result = string.Empty; string Par_Out_UserRole = string.Empty; string tmp_IPAddress = context.Connection.RemoteIpAddress.ToString(); await TS.AddVisitor(tmp_IPAddress); await TS.AddActivityLog("AllUser", "Token generation for " + tmp_IPAddress, MethodBase.GetCurrentMethod()); var identity = await GetIdentity(UserName, UserPass, tmp_IPAddress, MachineID, tmpWebApiUserType, out Par_Out_Result, out Par_Out_UserRole); if (identity == null) { var error_response = new { Access_token = "", Expires_in = 0, Error_Message = Par_Out_Result }; // Serialize and return the response context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(error_response, new JsonSerializerSettings { Formatting = Formatting.Indented })); return; } var now = DateTime.UtcNow; TimeSpan span = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)); double unixTime = span.TotalSeconds; // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims. // You can add other claims here, if you want: var claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, "tmp_User"), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64), new Claim("UserID", Par_Out_Result), //encrypted new Claim("UserName", GlobalFunctions.CmdAsymmetricEncrypt(UserName.ToLower() + GlobalFunctions.GetRandomAlphaNumeric(10))), //encrypted //new Claim("MyClientAsymPK", context.Request.Form["MyClientAsymPK"]), //encrypted new Claim("ClientSymmKey", context.Request.Form["ClientSymmKey"]), //encrypted new Claim("ClientSymmIV", context.Request.Form["ClientSymmIV"]), //encrypted new Claim("MachineID", context.Request.Form["MachineID"]), //encrypted new Claim("ClientIP", GlobalFunctions.CmdAsymmetricEncrypt(tmp_IPAddress + GlobalFunctions.GetRandomAlphaNumeric(10))), //encrypted new Claim("roles", Par_Out_UserRole), }; // Create the JWT and write it to a string var jwt = new JwtSecurityToken( issuer: _options.Issuer, audience: _options.Audience, claims: claims, notBefore: now, expires: now.Add(_options.Expiration), signingCredentials: _options.SigningCredentials); try { var response = new { Access_token = new JwtSecurityTokenHandler().WriteToken(jwt), Expires_in = (int)_options.Expiration.TotalSeconds, Error_Message = string.Empty }; // Serialize and return the response context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); } catch (Exception ex) { var response = new { Access_token = string.Empty, Expires_in = 0, Error_Message = ex.Message }; // Serialize and return the response context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented })); } }
private Task <ClaimsIdentity> GetIdentity(string Par_Username, string Par_Password, string Par_IPAddress, string Par_MachineID, WebApiUserTypesEnum ParWebApiUserType, out string Par_Out_Result, out string Par_Out_UserRole) { Par_Out_Result = string.Empty; Par_Out_UserRole = string.Empty; try { switch (ParWebApiUserType) { case WebApiUserTypesEnum.NotAuthorized: Par_Out_UserRole = "NotAutorizedUser"; if (Par_Username.Equals(GlobalData.NotAuthorizedUserName) && Par_Password.Equals(GlobalData.NotAuthorizedUserPass)) { Par_Out_Result = GlobalFunctions.CmdAsymmetricEncrypt("-745" + GlobalFunctions.GetRandomAlphaNumeric(10)); return(Task.FromResult(new ClaimsIdentity(new System.Security.Principal.GenericIdentity(Par_Username, "Token"), new Claim[] { }))); } else { Par_Out_Result = "Invalid NotAutorizedUser UserName or Password"; } break; case WebApiUserTypesEnum.Authorized: Par_Out_UserRole = "AutorizedUser"; TSUserEntity tsUserEntity = TS.FindUser(Par_Username, false, string.Empty).Result; if (tsUserEntity != null) { if (GlobalFunctions.CompareHash(Par_Password, tsUserEntity)) { Par_Out_Result = GlobalFunctions.CmdAsymmetricEncrypt(tsUserEntity.PartitionKey + GlobalFunctions.GetRandomAlphaNumeric(10)); return(Task.FromResult(new ClaimsIdentity(new System.Security.Principal.GenericIdentity(Par_Username, "Token"), new Claim[] { }))); } else { Par_Out_Result = "Invalid AutorizedUser Password"; } } else { Par_Out_Result = "Invalid AutorizedUser Name"; } break; case WebApiUserTypesEnum.Admin: Par_Out_UserRole = "Admin"; if (Par_IPAddress.Equals(GlobalData.AdminIPAddress)) { if (Par_MachineID.Equals(GlobalData.AdminMachineID)) { if (Par_Username.Equals(GlobalData.AdminUserName) && Par_Password.Equals(GlobalData.AdminUserPass)) { Par_Out_Result = GlobalFunctions.CmdAsymmetricEncrypt("-1" + GlobalFunctions.GetRandomAlphaNumeric(10)); return(Task.FromResult(new ClaimsIdentity(new System.Security.Principal.GenericIdentity(Par_Username, "Token"), new Claim[] { }))); } else { Par_Out_Result = "Invalid Admin UserName or Password"; } } else { Par_Out_Result = "Invalid Admin MachineID"; } } else { Par_Out_Result = "Invalid Admin IPAddress"; } break; default: break; } } catch (Exception ex) { bool b = TS.AddErrorLog("AllUsers", ex.Message, MethodBase.GetCurrentMethod()).Result; } // Credentials are invalid, or account doesn't exist return(Task.FromResult <ClaimsIdentity>(null)); }
public static async Task <bool> CmdGetJWT(SecureString ParUserName, SecureString ParPassword, WebApiUserTypesEnum ParWebApiUserTypesEnum = WebApiUserTypesEnum.NotAuthorized) { if (!LocalData.IsDownloadedSetupData) { LocalFunctions.AddError("Bootstrap data is not Downloaded!", MethodBase.GetCurrentMethod(), true, false); return(false); } LocalData.CurrJWT = string.Empty; try { JwtResult tmp_jwt = await WebApiFunctions.CmdDownloadToken(ParUserName, ParPassword, ParWebApiUserTypesEnum); if (string.IsNullOrEmpty(tmp_jwt.ErrorMessage)) { LocalData.CurrJWT = tmp_jwt.AccessToken; } else { LocalFunctions.AddError(tmp_jwt.ErrorMessage, MethodBase.GetCurrentMethod(), true, false); } } catch (Exception ex) { LocalFunctions.AddError(ex.Message, MethodBase.GetCurrentMethod(), true, false); } return(!string.IsNullOrEmpty(LocalData.CurrJWT)); }