public void RoundtripServiceIdentityThumbprintAuthTest_Device() { // Arrange var serviceAuthentication = new ServiceAuthentication(new X509ThumbprintAuthentication(Guid.NewGuid().ToString(), Guid.NewGuid().ToString())); var serviceIdentity = new ServiceIdentity( "d1", "12345", new List <string> { Constants.IotEdgeIdentityCapability }, serviceAuthentication, ServiceIdentityStatus.Enabled); // Act string json = serviceIdentity.ToJson(); var roundtripServiceIdentity = json.FromJson <ServiceIdentity>(); // Assert Assert.NotNull(roundtripServiceIdentity); Assert.Equal(serviceIdentity.DeviceId, roundtripServiceIdentity.DeviceId); Assert.Equal(serviceIdentity.Id, roundtripServiceIdentity.Id); Assert.Equal(serviceIdentity.ModuleId.OrDefault(), roundtripServiceIdentity.ModuleId.OrDefault()); Assert.Equal(serviceIdentity.Status, roundtripServiceIdentity.Status); Assert.Equal(serviceIdentity.GenerationId, roundtripServiceIdentity.GenerationId); Assert.Equal(serviceIdentity.Capabilities, roundtripServiceIdentity.Capabilities); Assert.Equal(serviceIdentity.Authentication.Type, roundtripServiceIdentity.Authentication.Type); Assert.True(serviceIdentity.Authentication.X509Thumbprint.HasValue); Assert.Equal(serviceIdentity.Authentication.X509Thumbprint.OrDefault().PrimaryThumbprint, roundtripServiceIdentity.Authentication.X509Thumbprint.OrDefault().PrimaryThumbprint); Assert.Equal(serviceIdentity.Authentication.X509Thumbprint.OrDefault().SecondaryThumbprint, roundtripServiceIdentity.Authentication.X509Thumbprint.OrDefault().SecondaryThumbprint); }
public async Task InitializeFromStoreTest() { // Arrange var iterator = new Mock <IServiceIdentitiesIterator>(); iterator.Setup(i => i.HasNext).Returns(true); iterator.Setup(i => i.GetNext()).ThrowsAsync(new InvalidOperationException("Some error")); var serviceProxy = new Mock <IServiceProxy>(); serviceProxy.Setup(s => s.GetServiceIdentitiesIterator()).Returns(iterator.Object); var store = GetEntityStore("cache"); var serviceAuthentication = new ServiceAuthentication(ServiceAuthenticationType.None); var si1 = new ServiceIdentity("d1", "1234", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled); var si2 = new ServiceIdentity("d2", "m1", "2345", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled); var storedSi1 = new DeviceScopeIdentitiesCache.StoredServiceIdentity(si1); await store.Put(si1.Id, storedSi1.ToJson()); var storedSi2 = new DeviceScopeIdentitiesCache.StoredServiceIdentity(si2); await store.Put(si2.Id, storedSi2.ToJson()); // Act IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy.Object, store, TimeSpan.FromHours(1)); Option <ServiceIdentity> receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1"); Option <ServiceIdentity> receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m1"); // Assert Assert.True(si1.Equals(receivedServiceIdentity1.OrDefault())); Assert.True(si2.Equals(receivedServiceIdentity2.OrDefault())); }
public void Login() { var username = usernameLabel.text; var password = passwordLabel.text; var request = new LoginRequest(); request.username = username; request.password = password; request.clientVersion = 0; request.dataVersion = 0; request.marketType = 0; var serviceClient = new SJServiceClient <LoginRequest, LoginResponse>(); serviceClient.Post(LoginRequest.uri, request, (response) => { Debug.Log("정상적으로 로그인 되었습니다"); //gemCountLabel.text = response.accountVo.gem.ToString(); ServiceAuthentication.SetAuthInfo(new RequestBase.AuthInfo() { username = request.username, authToken = response.authToken }); StartClient(); }, Error); }
public async Task GetServiceIdentityFromServiceTest() { // Arrange var store = GetEntityStore("cache"); var serviceAuthenticationNone = new ServiceAuthentication(ServiceAuthenticationType.None); var serviceAuthenticationSas = new ServiceAuthentication(new SymmetricKeyAuthentication(GetKey(), GetKey())); var si_device = new ServiceIdentity("d2", "1234", Enumerable.Empty <string>(), serviceAuthenticationNone, ServiceIdentityStatus.Enabled); var si_module = new ServiceIdentity("d1", "m1", "1234", Enumerable.Empty <string>(), serviceAuthenticationSas, ServiceIdentityStatus.Disabled); var serviceProxy = new Mock <IServiceProxy>(); serviceProxy.Setup(s => s.GetServiceIdentity("d2")).ReturnsAsync(Option.Some(si_device)); serviceProxy.Setup(s => s.GetServiceIdentity("d1", "m1")).ReturnsAsync(Option.Some(si_module)); DeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy.Object, store, TimeSpan.FromHours(1)); // Act Option <ServiceIdentity> deviceServiceIdentity = await deviceScopeIdentitiesCache.GetServiceIdentityFromService("d2"); Option <ServiceIdentity> moduleServiceIdentity = await deviceScopeIdentitiesCache.GetServiceIdentityFromService("d1/m1"); // Assert Assert.True(deviceServiceIdentity.HasValue); Assert.True(si_device.Equals(deviceServiceIdentity.OrDefault())); Assert.True(moduleServiceIdentity.HasValue); Assert.True(si_module.Equals(moduleServiceIdentity.OrDefault())); }
public async Task GetModuleOnBehalfOf() { // Setup ServiceIdentity results string parentEdgeId = "edge1"; string childEdgeId = "edge2"; string moduleId = "module1"; string deviceScope = "deviceScope1"; string parentScope = "parentScope1"; string generationId = "generation1"; var authentication = new ServiceAuthentication(new SymmetricKeyAuthentication(this.primaryKey, this.secondaryKey)); var resultDeviceIdentity = new ServiceIdentity(childEdgeId, null, deviceScope, new List <string>() { parentScope }, generationId, Enumerable.Empty <string>(), authentication, ServiceIdentityStatus.Enabled); var resultModuleIdentity = new ServiceIdentity(childEdgeId, moduleId, null, new List <string>() { deviceScope }, generationId, Enumerable.Empty <string>(), authentication, ServiceIdentityStatus.Enabled); var resultIdentities = new List <ServiceIdentity>() { resultDeviceIdentity, resultModuleIdentity }; var authChainMapping = new Dictionary <string, string>(); string targetId = childEdgeId + "/" + moduleId; authChainMapping.Add(targetId, $"{targetId};{childEdgeId};{parentEdgeId};edgeroot"); var controller = MakeController(childEdgeId, resultIdentities, authChainMapping); // Act controller.Request.Headers.Add(Constants.OriginEdgeHeaderKey, $"{childEdgeId}"); var request = new IdentityOnBehalfOfRequest(childEdgeId, moduleId, $"{childEdgeId};{parentEdgeId}"); await controller.GetDeviceAndModuleOnBehalfOfAsync(parentEdgeId, "$edgeHub", request); // Verify EdgeHub result types var expectedAuth = new AuthenticationMechanism() { SymmetricKey = new SymmetricKey() { PrimaryKey = this.primaryKey, SecondaryKey = this.secondaryKey } }; var expectedDeviceIdentities = new List <EdgeHubScopeDevice>() { new EdgeHubScopeDevice(childEdgeId, generationId, DeviceStatus.Enabled, expectedAuth, new DeviceCapabilities(), deviceScope, new List <string> { parentScope }) }; var expectedModuleIdentities = new List <EdgeHubScopeModule>() { new EdgeHubScopeModule(moduleId, childEdgeId, generationId, expectedAuth) }; var responseExpected = new EdgeHubScopeResultSuccess(expectedDeviceIdentities, expectedModuleIdentities); var responseExpectedJson = JsonConvert.SerializeObject(responseExpected); var responseActualBytes = GetResponseBodyBytes(controller); var responseActualJson = Encoding.UTF8.GetString(responseActualBytes); Assert.Equal((int)HttpStatusCode.OK, controller.HttpContext.Response.StatusCode); Assert.Equal(responseExpectedJson, responseActualJson); }
public void RoundtripServiceIdentityNoneAuthorityTest() { // Arrange var serviceAuthentication = new ServiceAuthentication(ServiceAuthenticationType.None); var serviceIdentity = new ServiceIdentity( "d1", "m1", "12345", new List <string>(), serviceAuthentication, ServiceIdentityStatus.Disabled); // Act string json = serviceIdentity.ToJson(); var roundtripServiceIdentity = json.FromJson <ServiceIdentity>(); // Assert Assert.NotNull(roundtripServiceIdentity); Assert.Equal(serviceIdentity.DeviceId, roundtripServiceIdentity.DeviceId); Assert.Equal(serviceIdentity.Id, roundtripServiceIdentity.Id); Assert.Equal(serviceIdentity.IsModule, roundtripServiceIdentity.IsModule); Assert.Equal(serviceIdentity.ModuleId.OrDefault(), roundtripServiceIdentity.ModuleId.OrDefault()); Assert.Equal(serviceIdentity.Status, roundtripServiceIdentity.Status); Assert.Equal(serviceIdentity.GenerationId, roundtripServiceIdentity.GenerationId); Assert.Equal(serviceIdentity.Capabilities, roundtripServiceIdentity.Capabilities); Assert.Equal(serviceIdentity.Authentication.Type, roundtripServiceIdentity.Authentication.Type); Assert.False(serviceIdentity.Authentication.X509Thumbprint.HasValue); Assert.False(serviceIdentity.Authentication.SymmetricKey.HasValue); }
internal RemoteServiceOptions(string baseAddress, long maxMessageSize, ServiceAuthentication authentication, Action <IServiceProvider, ChannelFactory> onChannelFactoryAction, Func <string, Type, string> addressConvention) { OnChannelFactoryAction = onChannelFactoryAction; Authentication = authentication; BaseAddress = baseAddress; MaxMessageSize = maxMessageSize; AddressConvention = addressConvention ?? new Func <string, Type, string>((ba, contract) => $"{ba.TrimEnd('/')}/{contract.Name.Substring(1)}.svc"); }
public void TestHandleServiceIdentityUpdateSuccess() { // Arrange var connectionManager = new Mock <IConnectionManager>(MockBehavior.Strict); var authenticator = new Mock <IAuthenticator>(MockBehavior.Strict); var credentialsStore = new Mock <ICredentialsCache>(MockBehavior.Strict); var deviceScopeIdentitiesCache = new Mock <IDeviceScopeIdentitiesCache>(MockBehavior.Strict); var deviceConnectivityManager = Mock.Of <IDeviceConnectivityManager>(); TimeSpan reauthFrequency = TimeSpan.FromSeconds(3); var deviceIdentity = new DeviceIdentity(IoTHubHostName, "d1"); var moduleIdentity = new ModuleIdentity(IoTHubHostName, "d1", "m1"); var deviceCredentials = Mock.Of <IClientCredentials>(c => c.Identity == deviceIdentity && c.AuthenticationType == AuthenticationType.SasKey); var moduleCredentials = Mock.Of <IClientCredentials>(c => c.Identity == moduleIdentity && c.AuthenticationType == AuthenticationType.SasKey); credentialsStore.Setup(c => c.Get(deviceIdentity)).ReturnsAsync(Option.Some(deviceCredentials)); credentialsStore.Setup(c => c.Get(moduleIdentity)).ReturnsAsync(Option.Some(moduleCredentials)); var deviceProxy = Mock.Of <IDeviceProxy>(d => d.IsActive && d.Identity == deviceIdentity); var moduleProxy = Mock.Of <IDeviceProxy>(d => d.IsActive && d.Identity == moduleIdentity); connectionManager.Setup(c => c.GetDeviceConnection("d1")).Returns(Option.Some(deviceProxy)); connectionManager.Setup(c => c.GetDeviceConnection("d1/m1")).Returns(Option.Some(moduleProxy)); connectionManager.Setup(c => c.RemoveDeviceConnection("d1")).Returns(Task.CompletedTask); connectionManager.Setup(c => c.RemoveDeviceConnection("d1/m1")).Returns(Task.CompletedTask); authenticator.Setup(a => a.ReauthenticateAsync(deviceCredentials)).ReturnsAsync(true); authenticator.Setup(a => a.ReauthenticateAsync(moduleCredentials)).ReturnsAsync(true); var serviceAuthentication = new ServiceAuthentication(ServiceAuthenticationType.None); var deviceServiceIdentity = new ServiceIdentity("d1", "1234", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled); var moduleServiceIdentity = new ServiceIdentity("d1/m1", "1234", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled); // Act var connectionReauthenticator = new ConnectionReauthenticator( connectionManager.Object, authenticator.Object, credentialsStore.Object, deviceScopeIdentitiesCache.Object, reauthFrequency, Mock.Of <IIdentity>(e => e.Id == "ed/$edgeHub"), deviceConnectivityManager); deviceScopeIdentitiesCache.Raise(d => d.ServiceIdentityUpdated += null, null, deviceServiceIdentity); deviceScopeIdentitiesCache.Raise(d => d.ServiceIdentityUpdated += null, null, moduleServiceIdentity); // Assert Assert.NotNull(connectionReauthenticator); connectionManager.Verify(c => c.RemoveDeviceConnection("d1"), Times.Never); connectionManager.Verify(c => c.RemoveDeviceConnection("d1/m1"), Times.Never); connectionManager.Verify(c => c.GetDeviceConnection("d1"), Times.Once); connectionManager.Verify(c => c.GetDeviceConnection("d1/m1"), Times.Once); authenticator.VerifyAll(); credentialsStore.VerifyAll(); deviceScopeIdentitiesCache.VerifyAll(); }
public IQueryable <LaterRatedIssue> GetLaterRatedIssues() { if (ServiceAuthentication.IsValid()) { return(this.ObjectContext.LaterRatedIssues); } else { //// throw fault throw new FaultException <InvalidOperationException>(new InvalidOperationException("Invalid credentials"), "Invalid credentials"); } }
public IQueryable <ConversationMessage> GetConversationMessages() { if (ServiceAuthentication.IsValid()) { return(this.ObjectContext.ConversationMessages); } else { //// throw fault throw new FaultException <InvalidOperationException>(new InvalidOperationException("Invalid credentials"), "Invalid credentials"); } }
public IQueryable <PreferenceSetOrganization> GetPreferenceSetOrganizations() { if (ServiceAuthentication.IsValid()) { return(this.ObjectContext.PreferenceSetOrganizations); } else { //// throw fault throw new FaultException <InvalidOperationException>(new InvalidOperationException("Invalid credentials"), "Invalid credentials"); } }
public bool ProcessRequest(IServiceContext context) { this.currentContext = context; if (context.Request.MethodName.Substring(0, 5) == "Login") { this.User = new UserModel(); this.User.LoginName = (string)context.Request.Parameters[0]; this.User.LoginPwd = (string)context.Request.Parameters[1]; //Login2 方法为加密的登陆方法 if (context.Request.MethodName == "Login2") { this.User.LoginName = EncryptHelper.DesDecrypt(this.User.LoginName); this.User.LoginPwd = EncryptHelper.DesDecrypt(this.User.LoginPwd); } UserLoginInfoModel result = Login(); if (result.LoginResult) { //分配服务地址 DispatchService disp = new DispatchService(); disp.CurrentContext = context; ServiceRegModel server = disp.DoDispatch(); //在外网测试有问提,暂时屏蔽 2012.5.24 result.ServiceUri = server.GetUri(); //如果登录成功,设置登录凭据 ServiceIdentity newUser = new ServiceIdentity(); newUser.Id = result.User.UserID; newUser.Name = result.User.LoginName; newUser.Expire = new TimeSpan(0, 0, 20); //20秒过期,客户端必须订阅CheckUserIdentity 方法 newUser.IsAuthenticated = true; newUser.Uri = result.ServiceUri; System.Diagnostics.Debug.WriteLine("--------------newUser.Uri={0} ; Client IP:{1}", newUser.Uri, context.Request.ClientIP); ServiceAuthentication auth = new ServiceAuthentication(context); //如果相同的用户账号已经在别的机器登录过,则取消之前的登录凭据 ServiceIdentity oldUser = auth.FindIdentity(newUser); if (oldUser != null) { auth.SignOut(oldUser); } auth.Authenticate(newUser); } context.Response.WriteJsonString(result); return(false); } context.SessionRequired = true; return(true); }
/// <summary> /// 在系统中检查用户登录的凭据是否还在 /// </summary> /// <param name="uid"></param> /// <returns></returns> public bool CheckUserIdentity() { //假设服务上有300个用户,没处理一次,需要9秒左右,加上轮询间隔,总共不超过15秒 //执行该方法的总的时间必须 小于每个凭据的过期时间 currentContext.BatchInterval = 5000; currentContext.ParallelExecute = false; System.Diagnostics.Debug.WriteLine("--------------CheckUserIdentity Client IP:{0},{1}", this.currentContext.Request.ClientIP, this.currentContext.Request.ClientIdentity); ServiceAuthentication auth = new ServiceAuthentication(this.currentContext); ServiceIdentity user = auth.GetIdentity(); return(user != null); }
/// <summary> /// 注销登录 /// </summary> /// <returns></returns> public bool Logout() { ServiceAuthentication auth = new ServiceAuthentication(this.currentContext); ServiceIdentity user = auth.GetIdentity(); if (user != null) { UserBIZ biz = new UserBIZ(); biz.SaveLogoutLog(user.Id); return(auth.SignOut(user)); } return(false); }
private void ButtonSignup_Click(object sender, RoutedEventArgs e) { string mail = TextBoxMail.Text; string password = TextBoxPassword.Password; string confirmPassword = TextBoxConfirmPassword.Password; string firstName = TextBoxFirstName.Text; string lastName = TextBoxLastName.Text; string phone = TextBoxPhone.Text; Validator validator = new Validator(new List <Input> { new Input("email", mail), new Input("password", password), new Input("confirm", password, confirmPassword) }); //Affiche les erreurs if (validator.HasErrors) { string message = ""; foreach (Input error in validator.Errors) { message += error.Message + Environment.NewLine; // Environment.NewLine=\n } MessageBox.Show(message); //Ouvre une nouvelle petite fenêtre pour afficher les erreurs } else { Client client = new Client(); client.Mail = mail; client.Password = password; client.FirstName = firstName; client.LastName = lastName; client.Phone = phone; ServiceAuthentication serviceAuthentication = new ServiceAuthentication(); if (serviceAuthentication.Signup(client)) { PageHome pageHome = new PageHome(); ((MainWindow)Parent).Content = pageHome; } else { MessageBox.Show("Sorry, something went wrong"); } } }
public async Task <ActionResult> Login(LoginModel loginModel, string returnUrl) { RedHawkToken redHawkToken = new RedHawkToken(); EncryptDecrypt encryptDecrypt = new EncryptDecrypt(); if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true if (loginModel != null) { ServiceAuthentication serviceAuthentication = new ServiceAuthentication(); redHawkToken = serviceAuthentication.GetRedHawkServiceToken(loginModel); Session["RedHawkToken"] = redHawkToken; if (redHawkToken.IsAuthenticated) { var result = await ValidateLogin(loginModel); switch (result) { case SignInStatus.Success: { return(RedirectToAction("Index", "Home")); } case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = loginModel.RememberMe })); case SignInStatus.Failure: default: ViewBag.ErrorMessage = "The user name or password provided is incorrect"; return(View(loginModel)); } } else { ViewBag.ErrorMessage = "The user name or password provided is incorrect"; } } } // If we got this far, something failed, redisplay form return(View(loginModel)); }
private void ButtonForgotPassword_Click(object sender, RoutedEventArgs e) { string mail = TextBoxMail.Text; ServiceAuthentication serviceAuthentication = new ServiceAuthentication(); string password = serviceAuthentication.ForgotPassword(mail); if (password != null) { StackPanelPassword.Visibility = Visibility.Visible; TextBlockPassword.Text = password; } else { MessageBox.Show("Your mail does not exist in our database"); } }
private void ButtonLogin_Click(object sender, RoutedEventArgs e) { string mail = TextBoxMail.Text; string password = TextBoxPassword.Password; ServiceAuthentication serviceAuthentication = new ServiceAuthentication(); bool isAuth = serviceAuthentication.Authenticate(mail, password); if (isAuth) { PageHome pageHome = new PageHome(); ((MainWindow)Parent).Content = pageHome; } else { MessageBox.Show("Vos identifiants sont erronés, veuillez réessayer"); } }
static AuthenticationMechanism GetAuthenticationMechanism(ServiceAuthentication serviceAuth) { var authentication = new AuthenticationMechanism(); switch (serviceAuth.Type) { case ServiceAuthenticationType.SymmetricKey: authentication.Type = AuthenticationType.Sas; var sasKey = serviceAuth.SymmetricKey.Expect(() => new InvalidOperationException("SAS key shouldn't be empty when auth type is SymmetricKey")); authentication.SymmetricKey = new SymmetricKey() { PrimaryKey = sasKey.PrimaryKey, SecondaryKey = sasKey.SecondaryKey }; break; case ServiceAuthenticationType.CertificateThumbprint: authentication.Type = AuthenticationType.SelfSigned; var x509Thumbprint = serviceAuth.X509Thumbprint.Expect(() => new InvalidOperationException("X509 thumbprint shouldn't be empty when auth type is CertificateThumbPrint")); authentication.X509Thumbprint = new X509Thumbprint() { PrimaryThumbprint = x509Thumbprint.PrimaryThumbprint, SecondaryThumbprint = x509Thumbprint.SecondaryThumbprint }; break; case ServiceAuthenticationType.CertificateAuthority: authentication.Type = AuthenticationType.CertificateAuthority; break; case ServiceAuthenticationType.None: authentication.Type = AuthenticationType.None; break; default: throw new InvalidOperationException($"Unexpected ServiceAuthenticationType: {serviceAuth.Type}"); } return(authentication); }
public async Task RefreshCacheTest() { // Arrange var store = GetEntityStore("cache"); var serviceAuthentication = new ServiceAuthentication(ServiceAuthenticationType.None); Func <ServiceIdentity> si1 = () => new ServiceIdentity("d1", "1234", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled); Func <ServiceIdentity> si2 = () => new ServiceIdentity("d2", "m1", "2345", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled); Func <ServiceIdentity> si3 = () => new ServiceIdentity("d3", "5678", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled); Func <ServiceIdentity> si4 = () => new ServiceIdentity("d2", "m4", "9898", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled); var iterator1 = new Mock <IServiceIdentitiesIterator>(); iterator1.SetupSequence(i => i.HasNext) .Returns(true) .Returns(true) .Returns(false); iterator1.SetupSequence(i => i.GetNext()) .ReturnsAsync( new List <ServiceIdentity> { si1(), si2() }) .ReturnsAsync( new List <ServiceIdentity> { si3(), si4() }); var iterator2 = new Mock <IServiceIdentitiesIterator>(); iterator2.SetupSequence(i => i.HasNext) .Returns(true) .Returns(false); iterator2.SetupSequence(i => i.GetNext()) .ReturnsAsync( new List <ServiceIdentity> { si1(), si2(), si3() }); var serviceProxy = new Mock <IServiceProxy>(); serviceProxy.SetupSequence(s => s.GetServiceIdentitiesIterator()) .Returns(iterator1.Object) .Returns(iterator2.Object); var updatedIdentities = new List <ServiceIdentity>(); var removedIdentities = new List <string>(); // Act IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy.Object, store, TimeSpan.FromSeconds(8)); deviceScopeIdentitiesCache.ServiceIdentityUpdated += (sender, identity) => updatedIdentities.Add(identity); deviceScopeIdentitiesCache.ServiceIdentityRemoved += (sender, s) => removedIdentities.Add(s); // Wait for refresh to complete await Task.Delay(TimeSpan.FromSeconds(3)); Option <ServiceIdentity> receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1"); Option <ServiceIdentity> receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m1"); Option <ServiceIdentity> receivedServiceIdentity3 = await deviceScopeIdentitiesCache.GetServiceIdentity("d3"); Option <ServiceIdentity> receivedServiceIdentity4 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m4"); // Assert Assert.True(si1().Equals(receivedServiceIdentity1.OrDefault())); Assert.True(si2().Equals(receivedServiceIdentity2.OrDefault())); Assert.True(si3().Equals(receivedServiceIdentity3.OrDefault())); Assert.True(si4().Equals(receivedServiceIdentity4.OrDefault())); Assert.Empty(updatedIdentities); Assert.Empty(removedIdentities); // Wait for another refresh cycle to complete await Task.Delay(TimeSpan.FromSeconds(8)); receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1"); receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m1"); receivedServiceIdentity3 = await deviceScopeIdentitiesCache.GetServiceIdentity("d3"); receivedServiceIdentity4 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m4"); // Assert Assert.True(si1().Equals(receivedServiceIdentity1.OrDefault())); Assert.True(si2().Equals(receivedServiceIdentity2.OrDefault())); Assert.True(si3().Equals(receivedServiceIdentity3.OrDefault())); Assert.False(receivedServiceIdentity4.HasValue); Assert.Empty(updatedIdentities); Assert.Single(removedIdentities); Assert.Contains("d2/m4", removedIdentities); }
static void ValidateAuthentication(AuthenticationMechanism authenticationMechanism, ServiceAuthentication serviceIdentityAuthentication) { Assert.NotNull(serviceIdentityAuthentication); switch (authenticationMechanism.Type) { case AuthenticationType.Sas: Assert.Equal(ServiceAuthenticationType.SymmetricKey, serviceIdentityAuthentication.Type); Assert.True(serviceIdentityAuthentication.SymmetricKey.HasValue); Assert.False(serviceIdentityAuthentication.X509Thumbprint.HasValue); Assert.Equal(authenticationMechanism.SymmetricKey.PrimaryKey, serviceIdentityAuthentication.SymmetricKey.OrDefault().PrimaryKey); Assert.Equal(authenticationMechanism.SymmetricKey.SecondaryKey, serviceIdentityAuthentication.SymmetricKey.OrDefault().SecondaryKey); break; case AuthenticationType.CertificateAuthority: Assert.Equal(ServiceAuthenticationType.CertificateAuthority, serviceIdentityAuthentication.Type); Assert.False(serviceIdentityAuthentication.X509Thumbprint.HasValue); Assert.False(serviceIdentityAuthentication.SymmetricKey.HasValue); break; case AuthenticationType.SelfSigned: Assert.Equal(ServiceAuthenticationType.CertificateThumbprint, serviceIdentityAuthentication.Type); Assert.True(serviceIdentityAuthentication.X509Thumbprint.HasValue); Assert.False(serviceIdentityAuthentication.SymmetricKey.HasValue); Assert.Equal(authenticationMechanism.X509Thumbprint.PrimaryThumbprint, serviceIdentityAuthentication.X509Thumbprint.OrDefault().PrimaryThumbprint); Assert.Equal(authenticationMechanism.X509Thumbprint.SecondaryThumbprint, serviceIdentityAuthentication.X509Thumbprint.OrDefault().SecondaryThumbprint); break; case AuthenticationType.None: Assert.Equal(ServiceAuthenticationType.None, serviceIdentityAuthentication.Type); Assert.False(serviceIdentityAuthentication.X509Thumbprint.HasValue); Assert.False(serviceIdentityAuthentication.SymmetricKey.HasValue); break; } }
public async Task RefreshServiceIdentityTest_List() { // Arrange var store = new EntityStore <string, string>(new InMemoryDbStore(), "cache"); var serviceAuthenticationNone = new ServiceAuthentication(ServiceAuthenticationType.None); var serviceAuthenticationSas = new ServiceAuthentication(new SymmetricKeyAuthentication(GetKey(), GetKey())); var si1_initial = new ServiceIdentity("d1", "1234", Enumerable.Empty <string>(), serviceAuthenticationNone, ServiceIdentityStatus.Enabled); var si1_updated = new ServiceIdentity("d1", "1234", Enumerable.Empty <string>(), serviceAuthenticationSas, ServiceIdentityStatus.Enabled); var si2 = new ServiceIdentity("d2", "5678", Enumerable.Empty <string>(), serviceAuthenticationSas, ServiceIdentityStatus.Enabled); var iterator1 = new Mock <IServiceIdentitiesIterator>(); iterator1.SetupSequence(i => i.HasNext) .Returns(true) .Returns(false); iterator1.SetupSequence(i => i.GetNext()) .ReturnsAsync( new List <ServiceIdentity> { si1_initial, si2 }); var serviceProxy = new Mock <IServiceProxy>(); serviceProxy.Setup(s => s.GetServiceIdentitiesIterator()) .Returns(iterator1.Object); serviceProxy.Setup(s => s.GetServiceIdentity(It.Is <string>(id => id == "d1"))).ReturnsAsync(Option.Some(si1_updated)); serviceProxy.Setup(s => s.GetServiceIdentity(It.Is <string>(id => id == "d2"))).ReturnsAsync(Option.None <ServiceIdentity>()); var updatedIdentities = new List <ServiceIdentity>(); var removedIdentities = new List <string>(); // Act IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy.Object, store, TimeSpan.FromHours(1)); deviceScopeIdentitiesCache.ServiceIdentityUpdated += (sender, identity) => updatedIdentities.Add(identity); deviceScopeIdentitiesCache.ServiceIdentityRemoved += (sender, s) => removedIdentities.Add(s); // Wait for refresh to complete await Task.Delay(TimeSpan.FromSeconds(3)); Option <ServiceIdentity> receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1"); Option <ServiceIdentity> receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2"); // Assert Assert.True(si1_initial.Equals(receivedServiceIdentity1.OrDefault())); Assert.True(si2.Equals(receivedServiceIdentity2.OrDefault())); // Update the identities await deviceScopeIdentitiesCache.RefreshServiceIdentities(new[] { "d1", "d2" }); receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1"); receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2"); // Assert Assert.True(si1_updated.Equals(receivedServiceIdentity1.OrDefault())); Assert.False(receivedServiceIdentity2.HasValue); Assert.Equal(1, removedIdentities.Count); Assert.Equal("d2", removedIdentities[0]); Assert.Equal(1, updatedIdentities.Count); Assert.Equal("d1", updatedIdentities[0].Id); }
public async Task RefreshCacheWithRefreshRequestTest() { // Arrange var store = new EntityStore <string, string>(new InMemoryDbStore(), "cache"); var serviceAuthentication = new ServiceAuthentication(ServiceAuthenticationType.None); Func <ServiceIdentity> si1 = () => new ServiceIdentity("d1", "1234", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled); Func <ServiceIdentity> si2 = () => new ServiceIdentity("d2", "m1", "2345", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled); Func <ServiceIdentity> si3 = () => new ServiceIdentity("d3", "5678", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled); Func <ServiceIdentity> si4 = () => new ServiceIdentity("d2", "m4", "9898", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled); var iterator1 = new Mock <IServiceIdentitiesIterator>(); iterator1.SetupSequence(i => i.HasNext) .Returns(true) .Returns(true) .Returns(false); iterator1.SetupSequence(i => i.GetNext()) .ReturnsAsync( new List <ServiceIdentity> { si1(), si2() }) .ReturnsAsync( new List <ServiceIdentity> { si3(), si4() }); var iterator2 = new Mock <IServiceIdentitiesIterator>(); iterator2.SetupSequence(i => i.HasNext) .Returns(true) .Returns(false); iterator2.SetupSequence(i => i.GetNext()) .ReturnsAsync( new List <ServiceIdentity> { si1(), si2(), si3() }); var iterator3 = new Mock <IServiceIdentitiesIterator>(); iterator3.SetupSequence(i => i.HasNext) .Returns(true) .Returns(false); iterator3.SetupSequence(i => i.GetNext()) .ReturnsAsync( new List <ServiceIdentity> { si1(), si2() }); var iterator4 = new Mock <IServiceIdentitiesIterator>(); iterator4.SetupSequence(i => i.HasNext) .Returns(true) .Returns(false); iterator4.SetupSequence(i => i.GetNext()) .ReturnsAsync( new List <ServiceIdentity> { si3(), si4() }); var serviceProxy = new Mock <IServiceProxy>(); serviceProxy.SetupSequence(s => s.GetServiceIdentitiesIterator()) .Returns(iterator1.Object) .Returns(iterator2.Object) .Returns(iterator3.Object) .Returns(iterator4.Object); var updatedIdentities = new List <ServiceIdentity>(); var removedIdentities = new List <string>(); // Act IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy.Object, store, TimeSpan.FromSeconds(7)); deviceScopeIdentitiesCache.ServiceIdentityUpdated += (sender, identity) => updatedIdentities.Add(identity); deviceScopeIdentitiesCache.ServiceIdentityRemoved += (sender, s) => removedIdentities.Add(s); // Wait for refresh to complete await Task.Delay(TimeSpan.FromSeconds(3)); Option <ServiceIdentity> receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1"); Option <ServiceIdentity> receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m1"); Option <ServiceIdentity> receivedServiceIdentity3 = await deviceScopeIdentitiesCache.GetServiceIdentity("d3"); Option <ServiceIdentity> receivedServiceIdentity4 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m4"); // Assert Assert.True(si1().Equals(receivedServiceIdentity1.OrDefault())); Assert.True(si2().Equals(receivedServiceIdentity2.OrDefault())); Assert.True(si3().Equals(receivedServiceIdentity3.OrDefault())); Assert.True(si4().Equals(receivedServiceIdentity4.OrDefault())); Assert.Equal(0, updatedIdentities.Count); Assert.Equal(0, removedIdentities.Count); // Act - Signal refresh cache multiple times. It should get picked up twice. deviceScopeIdentitiesCache.InitiateCacheRefresh(); deviceScopeIdentitiesCache.InitiateCacheRefresh(); deviceScopeIdentitiesCache.InitiateCacheRefresh(); deviceScopeIdentitiesCache.InitiateCacheRefresh(); // Wait for the 2 refresh cycles to complete, this time because of the refresh request await Task.Delay(TimeSpan.FromSeconds(5)); receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1"); receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m1"); receivedServiceIdentity3 = await deviceScopeIdentitiesCache.GetServiceIdentity("d3"); receivedServiceIdentity4 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m4"); // Assert Assert.True(si1().Equals(receivedServiceIdentity1.OrDefault())); Assert.True(si2().Equals(receivedServiceIdentity2.OrDefault())); Assert.False(receivedServiceIdentity3.HasValue); Assert.False(receivedServiceIdentity4.HasValue); Assert.Equal(0, updatedIdentities.Count); Assert.Equal(2, removedIdentities.Count); Assert.True(removedIdentities.Contains("d2/m4")); Assert.True(removedIdentities.Contains("d3")); // Wait for another refresh cycle to complete, this time because timeout await Task.Delay(TimeSpan.FromSeconds(8)); receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1"); receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m1"); receivedServiceIdentity3 = await deviceScopeIdentitiesCache.GetServiceIdentity("d3"); receivedServiceIdentity4 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m4"); // Assert Assert.True(si3().Equals(receivedServiceIdentity3.OrDefault())); Assert.True(si4().Equals(receivedServiceIdentity4.OrDefault())); Assert.False(receivedServiceIdentity1.HasValue); Assert.False(receivedServiceIdentity2.HasValue); Assert.Equal(0, updatedIdentities.Count); Assert.Equal(4, removedIdentities.Count); Assert.True(removedIdentities.Contains("d2/m1")); Assert.True(removedIdentities.Contains("d1")); }
public RemoteServiceOptionsBuilder Credentials(ServiceAuthentication auth) { this.Authentication = auth; return(this); }
public AuthenticationController(IConfiguration config, IServiceManageUser serviceManageUser) { _configuration = config; _serviceAuthentication = new ServiceAuthentication(config, serviceManageUser); _serviceManageUser = serviceManageUser; }
public async Task GetDevicesAndModulesInTargetDeviceScope_RoundTripTest() { // Setup ServiceIdentity results string parentEdgeId = "edge1"; string childEdgeId = "edge2"; string deviceId = "device1"; string moduleId = "module1"; string deviceScope = "deviceScope1"; string parentScope = "parentScope1"; string generationId = "generation1"; string primaryKey = "t3LtII3CppvtVqycKp9bo043vCEgWbGBJAzXZNmoBXo="; string secondaryKey = "kT4ac4PpH5UY0vA1JpLQWOu2yG6qKoqwvzee3j1Z3bA="; var authentication = new ServiceAuthentication(new SymmetricKeyAuthentication(primaryKey, secondaryKey)); var resultDeviceIdentity = new ServiceIdentity(deviceId, null, deviceScope, new List <string>() { parentScope }, generationId, Enumerable.Empty <string>(), authentication, ServiceIdentityStatus.Enabled); var resultModuleIdentity = new ServiceIdentity(deviceId, moduleId, null, new List <string>() { deviceScope }, generationId, Enumerable.Empty <string>(), authentication, ServiceIdentityStatus.Enabled); var resultIdentities = new List <ServiceIdentity>() { resultDeviceIdentity, resultModuleIdentity }; var authChainMapping = new Dictionary <string, string>(); authChainMapping.Add(childEdgeId, "edge2;edge1;edgeroot"); var controller = MakeController(childEdgeId, resultIdentities, authChainMapping); // Act var request = new NestedScopeRequest(0, string.Empty, "edge2;edge1"); await controller.GetDevicesAndModulesInTargetDeviceScopeAsync(parentEdgeId, "$edgeHub", request); // Verify EdgeHub result types var expectedAuth = new AuthenticationMechanism() { SymmetricKey = new SymmetricKey() { PrimaryKey = primaryKey, SecondaryKey = secondaryKey } }; var expectedDeviceIdentities = new List <EdgeHubScopeDevice>() { new EdgeHubScopeDevice(deviceId, generationId, DeviceStatus.Enabled, expectedAuth, new DeviceCapabilities(), deviceScope, new List <string> { parentScope }) }; var expectedModuleIdentities = new List <EdgeHubScopeModule>() { new EdgeHubScopeModule(moduleId, deviceId, generationId, expectedAuth) }; var responseExpected = new EdgeHubScopeResultSuccess(expectedDeviceIdentities, expectedModuleIdentities); var responseExpectedJson = JsonConvert.SerializeObject(responseExpected); var responseActualBytes = GetResponseBodyBytes(controller); var responseActualJson = Encoding.UTF8.GetString(responseActualBytes); Assert.Equal((int)HttpStatusCode.OK, controller.HttpContext.Response.StatusCode); Assert.Equal(responseExpectedJson, responseActualJson); // Deserialize JSON back to SDK result types var scopeResult = JsonConvert.DeserializeObject <ScopeResult>(responseActualJson); // Convert to original ServiceIdentity type Assert.Equal(1, (int)scopeResult.Devices.Count()); Assert.Equal(1, (int)scopeResult.Modules.Count()); ServiceIdentity device = scopeResult.Devices.First().ToServiceIdentity(); ServiceIdentity module = scopeResult.Modules.First().ToServiceIdentity(); Assert.Equal(resultDeviceIdentity, device); Assert.Equal(resultModuleIdentity, module); }
public async Task GetServiceIdentityTest_Module() { // Arrange var store = GetEntityStore("cache"); var serviceAuthenticationNone = new ServiceAuthentication(ServiceAuthenticationType.None); var serviceAuthenticationSas = new ServiceAuthentication(new SymmetricKeyAuthentication(GetKey(), GetKey())); var si1_initial = new ServiceIdentity("d1", "m1", "1234", Enumerable.Empty <string>(), serviceAuthenticationNone, ServiceIdentityStatus.Enabled); var si1_updated = new ServiceIdentity("d1", "m1", "1234", Enumerable.Empty <string>(), serviceAuthenticationSas, ServiceIdentityStatus.Disabled); var si2 = new ServiceIdentity("d2", "m2", "5678", Enumerable.Empty <string>(), serviceAuthenticationSas, ServiceIdentityStatus.Enabled); var si3 = new ServiceIdentity("d3", "m3", "0987", Enumerable.Empty <string>(), serviceAuthenticationSas, ServiceIdentityStatus.Enabled); var iterator1 = new Mock <IServiceIdentitiesIterator>(); iterator1.SetupSequence(i => i.HasNext) .Returns(true) .Returns(false); iterator1.SetupSequence(i => i.GetNext()) .ReturnsAsync( new List <ServiceIdentity> { si1_initial, si2 }); var serviceProxy = new Mock <IServiceProxy>(); serviceProxy.Setup(s => s.GetServiceIdentitiesIterator()) .Returns(iterator1.Object); serviceProxy.Setup(s => s.GetServiceIdentity("d1", "m1")).ReturnsAsync(Option.Some(si1_updated)); serviceProxy.Setup(s => s.GetServiceIdentity("d2", "m2")).ReturnsAsync(Option.None <ServiceIdentity>()); serviceProxy.Setup(s => s.GetServiceIdentity("d3", "m3")).ReturnsAsync(Option.Some(si3)); var updatedIdentities = new List <ServiceIdentity>(); var removedIdentities = new List <string>(); // Act IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy.Object, store, TimeSpan.FromHours(1)); deviceScopeIdentitiesCache.ServiceIdentityUpdated += (sender, identity) => updatedIdentities.Add(identity); deviceScopeIdentitiesCache.ServiceIdentityRemoved += (sender, s) => removedIdentities.Add(s); // Wait for refresh to complete await Task.Delay(TimeSpan.FromSeconds(3)); Option <ServiceIdentity> receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1/m1"); Option <ServiceIdentity> receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m2"); Option <ServiceIdentity> receivedServiceIdentity3 = await deviceScopeIdentitiesCache.GetServiceIdentity("d3/m3"); // Assert Assert.True(si1_initial.Equals(receivedServiceIdentity1.OrDefault())); Assert.True(si2.Equals(receivedServiceIdentity2.OrDefault())); Assert.False(receivedServiceIdentity3.HasValue); // Get the identities with refresh receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1/m1", true); receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m2", true); receivedServiceIdentity3 = await deviceScopeIdentitiesCache.GetServiceIdentity("d3/m3", true); // Assert Assert.True(si1_initial.Equals(receivedServiceIdentity1.OrDefault())); Assert.True(si2.Equals(receivedServiceIdentity2.OrDefault())); Assert.True(si3.Equals(receivedServiceIdentity3.OrDefault())); Assert.Empty(removedIdentities); Assert.Empty(updatedIdentities); }