public void TokenIssuerTests2() { var secret = Guid.NewGuid().ToString(); var hmac = Guid.NewGuid().ToString(); var tc = new AuthTokenFactory(); tc.Initialize(secret, hmac, new TimeSpan(1, 0, 0), Environment.MachineName); var tc2 = new AuthTokenFactory(); tc2.Initialize(secret, hmac, new TimeSpan(1, 0, 0), "SecondName"); var authRequest = new AuthenticateRequest { ApplicationId = Guid.NewGuid().ToString(), UserId = "UserId" }; var token = tc.CreateAuthenticationToken(authRequest.UserId, authRequest); var encrypted = tc2.EncryptAuthenticationToken(token, true); AuthenticationToken token2; string errorMsg; tc.DecryptAuthenticationToken(encrypted, out token2, out errorMsg); Assert.That(token2.TokenIssuer, Is.EqualTo("SecondName")); }
public static void CheckEncryptedToken(AuthTokenFactory tokenFactory, LogCountGuard appCheckGuard, object encryptedToken, AuthenticationToken unencryptedToken, ApplicationAccount applicationAccount, bool binaryToken) { AuthenticationToken token; string errorMsg; if (binaryToken) { var binArray = encryptedToken as byte[]; if (binArray == null) { log.WarnFormat(appCheckGuard, "AppId Check: Failed to cast just created binary token to byte[]. AppId:{0}/{1}, token:'{2}'", unencryptedToken.ApplicationId, unencryptedToken.ApplicationVersion, encryptedToken); return; } if (!tokenFactory.DecryptAuthenticationTokenBynary(binArray, 0, binArray.Length, out token, out errorMsg)) { log.WarnFormat(appCheckGuard, "AppId Check: Failed to decrypt just created binary token. errorMsg:{0}, AppId:{1}/{2}, " + "unencryptedToken:{3}, token:{4}", errorMsg, unencryptedToken.ApplicationId, unencryptedToken.ApplicationVersion, Newtonsoft.Json.JsonConvert.SerializeObject(unencryptedToken), BitConverter.ToString(binArray)); return; } } else { var strToken = encryptedToken as string; if (string.IsNullOrEmpty(strToken)) { return; } if (!tokenFactory.DecryptAuthenticationToken(strToken, out token, out errorMsg)) { log.WarnFormat(appCheckGuard, "AppId Check: Failed to decrypt just created token. errorMsg:{0}, AppId:{1}/{2}, " + "unencryptedToken:{3}, token:{4}", errorMsg, unencryptedToken.ApplicationId, unencryptedToken.ApplicationVersion, Newtonsoft.Json.JsonConvert.SerializeObject(unencryptedToken), strToken); return; } } Guid guid; if (!Guid.TryParse(token.ApplicationId, out guid)) { log.WarnFormat(appCheckGuard, "AppId Check: Wrong appId in token after encryption. appId:{0}, account appId:{1}, unencryptedToken:{2}, token:{0}", token.ApplicationId, applicationAccount.ApplicationId, Newtonsoft.Json.JsonConvert.SerializeObject(unencryptedToken), encryptedToken); } }
public void TokenIssuerTests() { var secret = Guid.NewGuid().ToString(); var hmac = Guid.NewGuid().ToString(); var tc = new AuthTokenFactory(); tc.Initialize(secret, hmac, new TimeSpan(1, 0, 0), Environment.MachineName); var authRequest = new AuthenticateRequest { ApplicationId = Guid.NewGuid().ToString(), UserId = "UserId" }; var token = tc.CreateAuthenticationToken(authRequest.UserId, authRequest); Assert.AreEqual(Environment.MachineName, token.TokenIssuer); }
public static void CheckEncryptedToken(AuthTokenFactory tokenFactory, LogCountGuard appCheckGuard, object authToken, IAuthenticateRequest authenticateRequest, ApplicationAccount applicationAccount, bool useV1Token) { var strToken = authToken as string; if (string.IsNullOrEmpty(strToken)) { return; } AuthenticationToken token; string errorMsg; if (useV1Token) { if (!tokenFactory.DecryptAuthenticationTokenV1(strToken, out token, out errorMsg)) { log.WarnFormat(appCheckGuard, "AppId Check: Failed to decrypt just created V1 token. errorMsg:{3}, AppId:{0}/{1}, token:{2}", authenticateRequest.ApplicationId, authenticateRequest.ApplicationVersion, authToken, errorMsg); return; } } else { if (!tokenFactory.DecryptAuthenticationTokenV2(strToken, out token, out errorMsg)) { log.WarnFormat(appCheckGuard, "AppId Check: Failed to decrypt just created V2 token. ErrorMsg:{3}, AppId:{0}/{1}, token:{2}", authenticateRequest.ApplicationId, authenticateRequest.ApplicationVersion, authToken, errorMsg); return; } } Guid guid; if (!Guid.TryParse(token.ApplicationId, out guid)) { log.WarnFormat(appCheckGuard, "AppId Check: Wrong appId in token after encryption. appId:{0}, account appId:{1}, request appId:{2}, token:{0}", token.ApplicationId, applicationAccount.ApplicationId, authenticateRequest.ApplicationId, authToken); } }
public void BinaryFormatTests() { var secret = Guid.NewGuid().ToString(); var hmac = Guid.NewGuid().ToString(); var tc = new AuthTokenFactory(); tc.Initialize(secret, hmac, new TimeSpan(0, 1, 0, 0), Environment.MachineName); var authRequest = new AuthenticateRequest { ApplicationId = Guid.NewGuid().ToString(), UserId = "UserId" }; var token = tc.CreateAuthenticationToken(authRequest.UserId, authRequest); var tokenByteArray = tc.EncryptAuthenticationTokenBinary(token, false); string errorMsg; Assert.That(tc.DecryptAuthenticationTokenBynary(tokenByteArray, 0, tokenByteArray.Length, out token, out errorMsg), Is.True); }
public void FinalExpireAtTests() { var secret = Guid.NewGuid().ToString(); var hmac = Guid.NewGuid().ToString(); var tc = new AuthTokenFactory(); tc.Initialize(secret, hmac, new TimeSpan(1, 0, 0), Environment.MachineName); var authRequest = new AuthenticateRequest { ApplicationId = Guid.NewGuid().ToString(), UserId = "UserId" }; var token = tc.CreateAuthenticationToken(authRequest.UserId, authRequest); token.FinalExpireAtTicks = DateTime.UtcNow.Add(new TimeSpan(1, 0, 1)).Ticks; Thread.Sleep(100); var tokenByteArray = tc.EncryptAuthenticationTokenBinary(token, true); AuthenticationToken token2; string errorMsg; Assert.That(tc.DecryptAuthenticationTokenBynary(tokenByteArray, 0, tokenByteArray.Length, out token2, out errorMsg), Is.True); Assert.AreEqual(token.FinalExpireAtTicks, token2.FinalExpireAtTicks); Assert.AreEqual(token.ExpireAtTicks, token2.ExpireAtTicks); tokenByteArray = tc.EncryptAuthenticationTokenBinary(token, true); Assert.Less(token2.ExpireAtTicks, token.ExpireAtTicks); AuthenticationToken token3; Assert.That(tc.DecryptAuthenticationTokenBynary(tokenByteArray, 0, tokenByteArray.Length, out token3, out errorMsg), Is.True); Assert.AreEqual(token.FinalExpireAtTicks, token3.FinalExpireAtTicks); Assert.AreEqual(token.ExpireAtTicks, token3.ExpireAtTicks); }
public SelfMonitoring(string settings, string gameIP, int gamePort, AuthTokenFactory authTokenFactory) { var split = settings.Split(';'); if (split.Length != 4) { log.WarnFormat("SelfMonitoring, settings length expected to be 4, was {0}: {1}", split.Length, settings); return; } this.appId = split[0]; if (!int.TryParse(split[1], out numGames)) { log.WarnFormat("SelfMonitoring, cannot parse '{0}' (numGames)", split[1]); return; } if (!int.TryParse(split[2], out numClients)) { log.WarnFormat("SelfMonitoring, cannot parse '{0}' (numClients)", split[2]); return; } if (!int.TryParse(split[3], out sendInterval)) { log.WarnFormat("SelfMonitoring, cannot parse '{0}' (sendInterval)", split[3]); return; } this.gameIP = gameIP; this.gamePort = gamePort; this.authTokenFactory = authTokenFactory; clients = new List <TestClient>(); if (log.IsInfoEnabled) { log.InfoFormat("SelfMonitoring, appId '{0}', numGames {1}, numClients {2}, sendInterval {3}, machineName {4}, gameIP {5}, gamePort {6}", appId, numGames, numClients, sendInterval, Environment.MachineName, gameIP, gamePort); } }
public override async Task <ServiceResponse <AuthToken> > GetAuthToken( string username, string password, AuthToken authToken, Dictionary <string, string> headers) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { throw new UnauthorizedAccessException("Invalid credential"); } string tokenReponse = string.Empty; HttpResponseMessage response = null; var success = IsHostReachable(); var sw = new Stopwatch(); sw.Start(); var tokenEndpointUrl = new Uri(Configuration.AuthUrl).ToString(); using (var client = new HttpClient()) { if (headers != null) { foreach (var header in headers) { client.DefaultRequestHeaders.Add(header.Key, header.Value); } } try { var data = $"{{\"email\":\"{username}\",\"password\":\"{password}\"}}"; var requestContent = new StringContent(data, Encoding.UTF8, MIME_JSON); response = await client.PostAsync(tokenEndpointUrl, requestContent); tokenReponse = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { sw.Stop(); if (client != null) { client.Dispose(); } return(new ServiceResponse <AuthToken>(ServiceStatus.Error, errorMessage: ex.Message, exception: ex)); } } switch (response?.StatusCode) { case HttpStatusCode.BadGateway: case HttpStatusCode.BadRequest: case HttpStatusCode.Forbidden: case HttpStatusCode.GatewayTimeout: case HttpStatusCode.InternalServerError: case HttpStatusCode.NoContent: case HttpStatusCode.NotAcceptable: case HttpStatusCode.NotFound: case HttpStatusCode.NotImplemented: case HttpStatusCode.RequestTimeout: case HttpStatusCode.Unauthorized: sw.Stop(); var errObj = JObject.Parse(tokenReponse); var errorDesc = errObj["message"].ToString(); return(new ServiceResponse <AuthToken>(ServiceStatus.Error, errorMessage: $"Authentication Failed: {errorDesc}", errorType: ServiceErrorType.Authentication)); default: break; } var tokenObj = JObject.Parse(tokenReponse); long ttl = 31536000; var authTokenNew = Configuration.AuthUrl.Contains("user_auth_tokens") ? AuthTokenFactory.CreateBasicAuthToken(tokenObj["token"].ToString(), null, Convert.ToInt64(tokenObj["ttl"])) : AuthTokenFactory.CreateBasicAuthToken(tokenObj["email"].ToString(), tokenObj["api_key"].ToString(), ttl); SetCurrentAuthToken(authTokenNew); SetStatusCode(response.StatusCode); var tokenResponse = new ServiceResponse <AuthToken>(ServiceStatus.Success, data: authTokenNew) { ElapsedTime = TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds) }; sw.Stop(); return(tokenResponse); }