/// <summary>
        /// Build and initialize an IdmNet Client object ready for use
        /// </summary>
        /// <returns>Newly initialized IdmNet Client</returns>
        public static IdmNetClient BuildClient()
        {
            var soapBinding = new IdmSoapBinding();
            string fqdn = GetEnvironmentSetting("MIM_fqdn");
            var endpointIdentity = EndpointIdentity.CreateSpnIdentity("FIMSERVICE/" + fqdn);

            var enumerationPath = "http://" + fqdn + SoapConstants.EnumeratePortAndPath;
            var factoryPath = "http://" + fqdn + SoapConstants.FactoryPortAndPath;
            var resourcePath = "http://" + fqdn + SoapConstants.ResourcePortAndPath;

            var enumerationEndpoint = new EndpointAddress(new Uri(enumerationPath), endpointIdentity);
            var factoryEndpoint = new EndpointAddress(new Uri(factoryPath), endpointIdentity);
            var resourceEndpoint = new EndpointAddress(new Uri(resourcePath), endpointIdentity);

            var searchClient = new SearchClient(soapBinding, enumerationEndpoint);
            var factoryClient = new ResourceFactoryClient(soapBinding, factoryEndpoint);
            var resourceClient = new ResourceClient(soapBinding, resourceEndpoint);

            var credentials = new NetworkCredential(
                GetEnvironmentSetting("MIM_username"),
                GetEnvironmentSetting("MIM_pwd"),
                GetEnvironmentSetting("MIM_domain"));

            searchClient.ClientCredentials.Windows.ClientCredential = credentials;
            factoryClient.ClientCredentials.Windows.ClientCredential = credentials;
            resourceClient.ClientCredentials.Windows.ClientCredential = credentials;

            var it = new IdmNetClient(searchClient, factoryClient, resourceClient);
            return it;
        }
        private void Listen(string app)
        {
            var config = DynamicConfigFactory.GetInstance($"{app}.status.properties");

            // 应用程序状态发生变化后,对应的Soa服务可用实例的清单也会发生变化
            config.RegisterListener(() =>
            {
                // 获取需要更新的服务清单
                var services = QueryServiceByAppId(app);

                // 获取AppInfo
                var appInfo = ResourceClient.AppInfoQuery(app);

                // 更新Soa在配置中心的可用实例列表
                services.ForEach(p =>
                {
                    var addressList = GetAvailableInstances(appInfo, config, p);
                    var address     = addressList == null ? string.Empty : string.Join(";", addressList);

                    logger.Info($"Update soa instances list : {address}");
                    // 更新配置中心的Soa对应的实例的清单
                    // 为了提高性能,如果Soa注册中心的服务采用集群的环境,那么需要一个Controller来控制和分配每一个实例支持不同的app
                    Modifier.Update($"soa.{p.ServiceId}.properties", new List <ModifiedPropertyInfo>()
                    {
                        new ModifiedPropertyInfo()
                        {
                            Key   = "ServerList",
                            Value = address
                        }
                    });
                });
            });
        }
Example #3
0
 private void SetExpiration(ResourceClient rc)
 {
     if (rc.AuthLevel == ClientAuthLevel.AuthorizedUser)
     {
         rc.Expiration = DateTime.Now.AddMonths(GetCurrentResource().AuthDuration);
     }
 }
Example #4
0
        public void CanDeleteAndCleanup()
        {
            if (!ExecuteCanDeleteAndCleanup)
            {
                Assert.Ignore("ExecuteCanDeleteAndCleanup is being ignored");
                return;
            }

            var items = GetAll();

            CheckAllList(items);
            foreach (var item in items)
            {
                if (!CanDelete(item))
                {
                    continue;
                }

                ResourceClient.Delete(item.Id());

                var deletedclient = ResourceClient.Get(item.Id());

                Assert.IsNull(deletedclient);
            }
        }
        public ResourceClient CreateResourceClient()
        {
            _resourceClient = new ResourceClient(_binding, _endpointAddress);
            SetCredenticalProperties <ResourceClient, Resource>(_resourceClient);

            return(_resourceClient);
        }
Example #6
0
        // connecting using ADWS
        // this function is here to optimize the connection
        // in a domain with W2003, ... not every server has ADWS installed
        // each binding try to resolve the dns entry which is taking some time ..
        // the trick is to test each ip and to assign a working one as the server
        public override void EstablishConnection()
        {
            if (Uri.CheckHostName(Server) != UriHostNameType.Dns)
            {
                Trace.WriteLine("Server is not a DNS entry - checking it directly");
                GetDomainInfo();
                return;
            }
            string initialServer = Server;

            Trace.WriteLine("Server is a DNS entry. Checking for connectity on each ip resolved");
            IPAddress[] addresses = null;
            try
            {
                addresses = Dns.GetHostEntry(Server).AddressList;
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Exception while resolving " + Server);
                Trace.WriteLine(ex.Message);
                Trace.WriteLine(ex.StackTrace);
                throw new EndpointNotFoundException("Unable to resolve the DNS address of " + Server + " (" + ex.Message + ")");
            }
            if (addresses.Length <= 1)
            {
                Trace.WriteLine("Only one server found");
                GetDomainInfo();
                return;
            }
            foreach (IPAddress ip in addresses)
            {
                try
                {
                    Server = ip.ToString();
                    Trace.WriteLine("Trying " + Server);
                    GetDomainInfo();
                    Trace.WriteLine("The connection worked");
                    return;
                }
                catch (EndpointNotFoundException ex)
                {
                    Trace.WriteLine("The connection didn't worked (EndpointNotFoundException)");
                    Trace.WriteLine("Exception: " + ex.Message);
                    CleanConnection <Resource>(_resource);
                    _resource = null;
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Exception: " + ex.Message);
                    Trace.WriteLine("Type: " + ex.GetType().ToString());
                    Trace.WriteLine("The connection didn't worked");
                    CleanConnection <Resource>(_resource);
                    _resource = null;
                }
            }
            Trace.WriteLine("No connection worked");
            Trace.WriteLine("Trying ldap to find DC (dns entries are limited by ad site)");
            EstablishADWSConnectionUsingDomainConnection(initialServer, addresses);
        }
Example #7
0
 private static void DeleteToolEngineer(ISession session, IResource res, Client c, GenericResult result)
 {
     if (Validate(res, c, result))
     {
         ResourceClientInfo rci = session.Query <ResourceClientInfo>().FirstOrDefault(x => x.ClientID == c.ClientID && x.ResourceID == res.ResourceID);
         if (Validate(rci, result))
         {
             ResourceClient rc = session.Single <ResourceClient>(rci.ResourceClientID);
             session.Delete(rc);
         }
     }
 }
Example #8
0
 public override void EstablishConnection()
 {
     if (Uri.CheckHostName(Server) != UriHostNameType.Dns)
     {
         Trace.WriteLine("Server is not a DNS entry - checking it directly");
         GetDomainInfo();
         return;
     }
     Trace.WriteLine("Trying to locate the domain");
     Trace.WriteLine("Locating a DC");
     try
     {
         Server = DomainLocator.GetDC(Server, true, false);
     }
     catch (Exception)
     {
         Trace.WriteLine("The domain location didn't worked - trying it directly");
         GetDomainInfo();
         return;
     }
     for (int i = 0; i < 2; i++)
     {
         try
         {
             Trace.WriteLine("Trying " + Server);
             GetDomainInfo();
             Trace.WriteLine("The connection worked");
             return;
         }
         catch (EndpointNotFoundException)
         {
             Trace.WriteLine("The connection didn't worked");
             CleanConnection <Resource>(_resource);
             _resource = null;
         }
         catch (Exception ex)
         {
             Trace.WriteLine("Exception: " + ex.Message);
             Trace.WriteLine("Type: " + ex.GetType().ToString());
             Trace.WriteLine("The connection didn't worked");
             CleanConnection <Resource>(_resource);
             _resource = null;
         }
         if (i > 0)
         {
             Server = DomainLocator.GetDC(Server, true, true);
         }
     }
     // if we coulnd't connect to the select DC, even after a refresh, go to exception
     throw new EndpointNotFoundException();
 }
Example #9
0
        public void CanCreateSingle()
        {
            if (!ExecuteCanCreateSingle)
            {
                Assert.Ignore("ExecuteCanCreateSingle is being ignored");
                return;
            }


            TSingle item = CreateSingleItemForInsert();

            TSingle result = ResourceClient.Put(item);

            CompareSingleItem(item, result);
        }
Example #10
0
        private static void AddToolEngineer(ISession session, IResource res, Client c, GenericResult result)
        {
            if (Validate(res, c, result))
            {
                ResourceClient rc = new ResourceClient
                {
                    AuthLevel              = ClientAuthLevel.ToolEngineer,
                    ClientID               = c.ClientID,
                    EmailNotify            = null,
                    Expiration             = null,
                    PracticeResEmailNotify = null,
                    ResourceID             = res.ResourceID
                };

                session.Insert(rc);
            }
        }
Example #11
0
        public void CanLoadById()
        {
            if (!ExecuteCanLoadById)
            {
                Assert.Ignore("ExecuteCanLoadById is being ignored");
                return;
            }

            var items = GetAll();

            CheckAllList(items);

            foreach (var item in items)
            {
                var newitem = ResourceClient.Get(item.Id());

                CompareSingleItem(item, newitem);
            }
        }
Example #12
0
        internal static string CheckServicePrincipalPermissions(ResourceClient resourceClient, KeyVaultClient keyVaultClient, string resourceGroupName, string keyVault, string kvSubscriptionId)
        {
            var kv = keyVaultClient.GetKeyVault(resourceGroupName, keyVault, kvSubscriptionId);

            foreach (var policy in kv.Properties.AccessPolicies)
            {
                if (policy.ObjectId == ("f8daea97-62e7-4026-becf-13c2ea98e8b4"))
                {
                    foreach (var perm in policy.Permissions.Secrets)
                    {
                        if (perm.ToLower() == "get")
                        {
                            return(perm);
                        }
                    }
                }
            }
            return(string.Empty);
        }
        internal static Certificate[] GetCertificates(ResourceClient resourceClient, WebsitesClient websitesClient, string resourceGroupName, string thumbPrint)
        {
            var certificateResources = resourceClient.ResourceManagementClient.FilterResources(new FilterResourcesOptions
            {
                ResourceGroup = resourceGroupName,
                ResourceType  = "Microsoft.Web/Certificates"
            }).ToArray();

            var certificates =
                certificateResources.Select(
                    certificateResource =>
                    websitesClient.GetCertificate(certificateResource.ResourceGroupName ?? GetResourceGroupFromResourceId(certificateResource.Id), certificateResource.Name));

            if (!string.IsNullOrEmpty(thumbPrint))
            {
                certificates = certificates.Where(c => string.Equals(c.Thumbprint, thumbPrint, StringComparison.OrdinalIgnoreCase)).ToList();
            }

            return(certificates.ToArray());
        }
        internal static string CheckServicePrincipalPermissions(ResourceClient resourceClient, KeyVaultClient keyVaultClient, string resourceGroupName, string keyVault)
        {
            var perm1 = " ";
            var kv2   = keyVaultClient.GetKeyVault(resourceGroupName, keyVault);

            foreach (var policy in kv2.Properties.AccessPolicies)
            {
                if (policy.ObjectId == ("f8daea97-62e7-4026-becf-13c2ea98e8b4"))
                {
                    foreach (var perm in policy.Permissions.Secrets)
                    {
                        if ((perm == "Get") || (perm == "get"))
                        {
                            perm1 = perm;
                            Console.WriteLine("Success");
                            break;
                        }
                    }
                }
            }
            return(perm1.ToString());
        }
        /// <summary>
        /// Build and initialize an IdmNet Client object ready for use
        /// </summary>
        /// <returns>Newly initialized IdmNet Client</returns>
        public static IdmNetClient BuildClient()
        {
            var    soapBinding      = new IdmSoapBinding();
            string fqdn             = GetEnvironmentSetting("MIM_fqdn");
            var    endpointIdentity = EndpointIdentity.CreateSpnIdentity("FIMSERVICE/" + fqdn);


            var enumerationPath = "http://" + fqdn + SoapConstants.EnumeratePortAndPath;
            var factoryPath     = "http://" + fqdn + SoapConstants.FactoryPortAndPath;
            var resourcePath    = "http://" + fqdn + SoapConstants.ResourcePortAndPath;


            var enumerationEndpoint = new EndpointAddress(new Uri(enumerationPath), endpointIdentity);
            var factoryEndpoint     = new EndpointAddress(new Uri(factoryPath), endpointIdentity);
            var resourceEndpoint    = new EndpointAddress(new Uri(resourcePath), endpointIdentity);


            var searchClient   = new SearchClient(soapBinding, enumerationEndpoint);
            var factoryClient  = new ResourceFactoryClient(soapBinding, factoryEndpoint);
            var resourceClient = new ResourceClient(soapBinding, resourceEndpoint);



            var credentials = new NetworkCredential(
                GetEnvironmentSetting("MIM_username"),
                GetEnvironmentSetting("MIM_pwd"),
                GetEnvironmentSetting("MIM_domain"));

            searchClient.ClientCredentials.Windows.ClientCredential   = credentials;
            factoryClient.ClientCredentials.Windows.ClientCredential  = credentials;
            resourceClient.ClientCredentials.Windows.ClientCredential = credentials;


            var it = new IdmNetClient(searchClient, factoryClient, resourceClient);

            return(it);
        }
Example #16
0
 /// <summary>
 /// Primary constructor for the IdmNetClient.  Though this is public and can be called, the normal thing to
 /// do is to use IdmNetClientFactory.BuildClient().  This is available in case you want to build the client
 /// based on different assumptions made by the factory builder.  For example, if you wanted to use a different
 /// client credentials mechanism, WCF binding, or endpoints
 /// </summary>
 /// <param name="searchClient">
 /// This is the SOAP client used to connect to Identity Manager for search functionality (WS-Enumeration - 
 /// Enumerate and Pull operations)
 /// </param>
 /// <param name="factoryClient">
 /// This is the SOAP client used to create new objects/resources in Identity Manager (WS-Transfer - Create 
 /// operation)
 /// </param>
 /// <param name="resourceClient">
 /// This is the SOAP client used to modify existing objects/resources in Identity Manager 
 /// </param>
 public IdmNetClient(SearchClient searchClient, ResourceFactoryClient factoryClient, ResourceClient resourceClient)
 {
     _searchClient = searchClient;
     _factoryClient = factoryClient;
     _resourceClient = resourceClient;
 }
Example #17
0
        public override void EstablishConnection()
        {
            if (Uri.CheckHostName(Server) != UriHostNameType.Dns)
            {
                Trace.WriteLine("Server is not a DNS entry - checking it directly");
                GetDomainInfo();
                return;
            }
            Domain domain = null;

            Trace.WriteLine("Trying to locate the domain");
            try
            {
                if (Credential != null)
                {
                    domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, Server, Credential.UserName, Credential.Password));
                }
                else
                {
                    domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, Server));
                }
                Trace.WriteLine("Domain located");
            }
            catch (ActiveDirectoryObjectNotFoundException ex)
            {
                Trace.WriteLine("Unable to get the domain info - trying direct connection");
                Trace.WriteLine("Exception: " + ex.Message);
                GetDomainInfo();
                return;
            }
            Trace.WriteLine("Locating a DC");
            Server = NativeMethods.GetDC(domain.Name, true, false);
            for (int i = 0; i < 2; i++)
            {
                try
                {
                    Trace.WriteLine("Trying " + Server);
                    GetDomainInfo();
                    Trace.WriteLine("The connection worked");
                    return;
                }
                catch (EndpointNotFoundException)
                {
                    Trace.WriteLine("The connection didn't worked");
                    CleanConnection <Resource>(_resource);
                    _resource = null;
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Exception: " + ex.Message);
                    Trace.WriteLine("Type: " + ex.GetType().ToString());
                    Trace.WriteLine("The connection didn't worked");
                    CleanConnection <Resource>(_resource);
                    _resource = null;
                }
                if (i > 0)
                {
                    Server = NativeMethods.GetDC(domain.Name, true, true);
                }
            }
        }
Example #18
0
 public IEnumerable <TSingle> ResourceFixtureAll()
 {
     return(ResourceClient.All());
 }
Example #19
0
 /// <summary>
 /// Primary constructor for the IdmNetClient.  Though this is public and can be called, the normal thing to
 /// do is to use IdmNetClientFactory.BuildClient().  This is available in case you want to build the client
 /// based on different assumptions made by the factory builder.  For example, if you wanted to use a different
 /// client credentials mechanism, WCF binding, or endpoints
 /// </summary>
 /// <param name="searchClient">
 /// This is the SOAP client used to connect to Identity Manager for search functionality (WS-Enumeration -
 /// Enumerate and Pull operations)
 /// </param>
 /// <param name="factoryClient">
 /// This is the SOAP client used to create new objects/resources in Identity Manager (WS-Transfer - Create
 /// operation)
 /// </param>
 /// <param name="resourceClient">
 /// This is the SOAP client used to modify existing objects/resources in Identity Manager
 /// </param>
 public IdmNetClient(SearchClient searchClient, ResourceFactoryClient factoryClient, ResourceClient resourceClient)
 {
     _searchClient   = searchClient;
     _factoryClient  = factoryClient;
     _resourceClient = resourceClient;
 }
Example #20
0
        public static async Task CreateVmAsync(
            string subscriptionId,
            string resourceGroup,
            string location,
            string vmName)
        {
            // Initialize Client
            var resourceClient = new ResourceClient(subscriptionId, new DefaultAzureCredential(true));
            var networkClient  = new NetworkClient(subscriptionId, new DefaultAzureCredential(true));
            var computeClient  = new ComputeClient(subscriptionId, new DefaultAzureCredential(true));

            // Create Resource Group
            await resourceClient.ResourceGroups.CreateOrUpdateAsync(resourceGroup, new ResourceGroup(location));

            // Create AvailabilitySet
            // TODO: Review initializer
            var availabilitySet = new AvailabilitySet(location);

            availabilitySet.PlatformFaultDomainCount  = 2;
            availabilitySet.PlatformUpdateDomainCount = 5;
            availabilitySet.Sku = new Sku()
            {
                Name = "Aligned"
            };

            availabilitySet = await computeClient.AvailabilitySets
                              .CreateOrUpdateAsync(resourceGroup, vmName + "_aSet", availabilitySet);

            // Create IP Address
            // TODO: Review other initializers
            var ipAddress = new PublicIPAddress();

            ipAddress.PublicIPAddressVersion   = IPVersion.IPv4;
            ipAddress.PublicIPAllocationMethod = IPAllocationMethod.Dynamic;
            ipAddress.Location = location;

            ipAddress = await networkClient
                        .PublicIPAddresses.StartCreateOrUpdate(resourceGroup, vmName + "_ip", ipAddress)
                        .WaitForCompletionAsync();

            // Create VNet
            var vnet = new VirtualNetwork();

            vnet.Location = location;
            vnet.AddAddressSpace("10.0.0.0/16");
            vnet.AddNewSubnet("mySubnet", "10.0.0.0/24");
            vnet.AddNewSubnet("mySubnet1", "10.0.1.0/24");

            vnet = await networkClient.VirtualNetworks
                   .StartCreateOrUpdate(resourceGroup, vmName + "_vent", vnet)
                   .WaitForCompletionAsync();

            // Create Network interface
            var nic = new NetworkInterface();

            nic.Location = location;
            nic.UseExistingVirtualNetwork(vnet, "mySubnet");
            nic.UseExistingPublicIP(ipAddress);

            nic = await networkClient.NetworkInterfaces
                  .StartCreateOrUpdate(resourceGroup, vmName + "_nic", nic)
                  .WaitForCompletionAsync();

            var vm = new VirtualMachine(location);

            vm.AddExistingNetworkInterface(nic.Id, true);
            vm.SetAvailabilitySet(availabilitySet.Id);
            vm.ConfigureLinuxWithPassword(
                VirtualMachineSizeTypes.StandardB1Ms,
                "testVM",
                "azureUser",
                "azure12345QWE!",
                configuration: new LinuxConfiguration {
                DisablePasswordAuthentication = false, ProvisionVMAgent = true
            });

            await computeClient.VirtualMachines
            .StartCreateOrUpdate(resourceGroup, vmName, vm)
            .WaitForCompletionAsync();
        }
Example #21
0
        public static async Task CreateVmAsync(
            string subscriptionId,
            string resourceGroup,
            string location,
            string vmName)
        {
            // Initialize Client
            var resourceClient = new ResourceClient(subscriptionId, new DefaultAzureCredential(true));
            var networkClient  = new NetworkClient(subscriptionId, new DefaultAzureCredential(true));
            var computeClient  = new ComputeClient(subscriptionId, new DefaultAzureCredential(true));

            // Create Resource Group
            await resourceClient.ResourceGroups.CreateOrUpdateAsync(resourceGroup, new ResourceGroup(location));

            // Create AvailabilitySet
            var availabilitySet = new AvailabilitySet(location);

            //// Following are optional, has default, probably no need for helpers as there are simple types.
            //// For other complex properties, need to evaluate common usage scenarios
            availabilitySet.PlatformFaultDomainCount  = 5;
            availabilitySet.PlatformUpdateDomainCount = 2;
            availabilitySet.Sku = new Sku()
            {
                Name = "Aligned"
            };

            availabilitySet = await computeClient.AvailabilitySets
                              .CreateOrUpdateAsync(resourceGroup, vmName + "_aSet", availabilitySet);

            // Create IP Address
            var ipAddress = new PublicIPAddress();

            // TODO Need to review. Downside of using string instead of enum is intellisense is messed up. But extensibility may trump this.
            // While . is easier to see intellisense, still does not give sense of necessary required properties.
            // Initializer helper should be added for initialization.
            ipAddress.PublicIPAddressVersion   = IPVersion.IPv4;
            ipAddress.PublicIPAllocationMethod = IPAllocationMethod.Dynamic;
            ipAddress.Location = location;

            ipAddress = await networkClient
                        .PublicIPAddresses.StartCreateOrUpdate(resourceGroup, vmName + "_ip", ipAddress)
                        .WaitForCompletionAsync();

            // Create VNet
            var vnet = new VirtualNetwork();

            vnet.Location = location;
            vnet.Subnets.Add(new Subnet()
            {
                Name = "name", AddressPrefix = "10.0.0.0/1"
            });
            vnet.AddressSpace.AddressPrefixes.Add("10.0.0.0/16");
            // TODO: vnet.Subnets.AddExistingSubnet("existing id");

            vnet = await networkClient.VirtualNetworks
                   .StartCreateOrUpdate(resourceGroup, vmName + "_vent", vnet)
                   .WaitForCompletionAsync();

            // Create Network interface
            var nic = new NetworkInterface();

            nic.Location = location;
            // TODO may need helper extensions for existing and new
            nic.IpConfigurations.Add(new NetworkInterfaceIPConfiguration()
            {
                Name    = "Primary",
                Primary = true,
                Subnet  = new Subnet()
                {
                    Id = vnet.Subnets.First().Id
                },
                PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                PublicIPAddress           = new PublicIPAddress()
                {
                    Id = ipAddress.Id
                }
            });

            nic = await networkClient.NetworkInterfaces
                  .StartCreateOrUpdate(resourceGroup, vmName + "_nic", nic)
                  .WaitForCompletionAsync();

            var vm = new VirtualMachine(location);

            vm.NetworkProfile = new NetworkProfile {
                NetworkInterfaces = new[] { new NetworkInterfaceReference()
                                            {
                                                Id = nic.Id
                                            } }
            };
            vm.AvailabilitySet.Id = availabilitySet.Id;
            vm.OsProfile          = new OSProfile
            {
                // TODO User name, password, SSH should have helpers
                ComputerName       = "testVM",
                AdminUsername      = "******",
                AdminPassword      = "******",
                LinuxConfiguration = new LinuxConfiguration
                {
                    DisablePasswordAuthentication = false, ProvisionVMAgent = true
                }
            };
            vm.StorageProfile = new StorageProfile()
            {
                ImageReference = new ImageReference()
                {
                    Offer     = "UbuntuServer",
                    Publisher = "Canonical",
                    Sku       = "18.04-LTS",
                    Version   = "latest"
                },
                DataDisks = new List <DataDisk>()
            };
            // vm.SetLatestWindowsImage();

            await computeClient.VirtualMachines
            .StartCreateOrUpdate(resourceGroup, vmName, vm)
            .WaitForCompletionAsync();
        }
Example #22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region 跨域
            services.AddCors(options =>
            {
                // this defines a CORS policy called "default"
                options.AddPolicy("default", policy =>
                {
                    policy.WithOrigins("http://localhost:2000")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });
            #endregion
            #region 读取配置信息
            var tokenSection = this.Configuration.GetSection("TokenConfig");
            var obj          = services.Configure <TokenConfig>(tokenSection);

            /*
             * 使用时重写构造函数,包含注入的配置信息
             *  public HomeController(IOptions<TokenConfig> setting) {
             *      TokenConfig = setting.Value;
             *  }
             */
            #endregion
            #region 客户端,密码模式
            ResourceClient.GetTokenConfig(tokenSection);//初始化配置文件
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(tokenSection)
            .AddResourceAndClient(services)
            .AddInMemoryApiResources(ResourceClient.GetApiResource())    //添加api资源
            .AddInMemoryClients(ResourceClient.GetClients())             //添加客户端
            .AddInMemoryIdentityResources(ResourceClient.GetIdentityResources())
            .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>();

            // .AddTestUsers(APIClient.GeTestUsers());//优化于上面的 ResourceOwnerPasswordValidator

            ////RSA:证书长度2048以上,否则抛异常
            ////配置AccessToken的加密证书
            //var rsa = new RSACryptoServiceProvider();
            ////从配置文件获取加密证书
            //rsa.ImportCspBlob(Convert.FromBase64String(Configuration["SigningCredential"]));
            ////IdentityServer4授权服务配置
            //services.AddIdentityServer()
            //    .AddSigningCredential(new RsaSecurityKey(rsa))    //设置加密证书
            //    //.AddTemporarySigningCredential()    //测试的时候可使用临时的证书
            //    .AddInMemoryScopes(TokenClient.GetScopes())
            //    .AddInMemoryClients(TokenClient.GetClients())
            //    //如果是client credentials模式那么就不需要设置验证User了
            //    .AddResourceOwnerValidator<MyUserValidator>() //User验证接口
            //    //.AddInMemoryUsers(OAuth2Config.GetUsers())    //将固定的Users加入到内存中
            //    ;

            #endregion
            #region 【方式1】JwtRegisteredClaimNames 方式 直接读取配置文件信息,初始化Token 需要验证的信息,如果不同在一台服务,则产生的Token与验证的Token的服务器验证信息与产生的信息要一致

            var symmetricKeyAsBase64      = tokenSection["Secret"];
            var keyByteArray              = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
            var signingKey                = new SymmetricSecurityKey(keyByteArray);
            var tokenValidationParameters = new TokenValidationParameters
            {
                #region  面三个参数是必须
                // 签名秘钥
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,
                // 发行者(颁发机构)
                ValidateIssuer = true,
                ValidIssuer    = tokenSection["Issuer"],
                // 令牌的观众(颁发给谁)
                ValidateAudience = true,
                ValidAudience    = tokenSection["Audience"],
                #endregion
                // 是否验证Token有效期
                ValidateLifetime = true,
                ClockSkew        = TimeSpan.Zero
                                   /***********************************TokenValidationParameters的参数默认值***********************************/
                                   // RequireSignedTokens = true,
                                   // SaveSigninToken = false,
                                   // ValidateActor = false,
                                   // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
                                   // ValidateAudience = true,
                                   // ValidateIssuer = true,
                                   // ValidateIssuerSigningKey = false,
                                   // 是否要求Token的Claims中必须包含Expires
                                   // RequireExpirationTime = true,
                                   // 允许的服务器时间偏移量
                                   // ClockSkew = TimeSpan.FromSeconds(300),//TimeSpan.Zero
                                   // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
                                   // ValidateLifetime = true
            };
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                //不使用https
                //o.RequireHttpsMetadata = false;
                o.TokenValidationParameters = tokenValidationParameters;
            });
            #endregion

            services.AddMvc();
        }
Example #23
0
        protected void SubmitButton_Command(object sender, CommandEventArgs e)
        {
            ShowErrorMessage(string.Empty);

            try
            {
                int             clientId;
                var             selectedAuthLevel = GetSelectedAuthLevel();
                var             resourceId        = GetCurrentResource().ResourceID;
                ClientAuthLevel refreshAuthLevel  = selectedAuthLevel;

                if (e.CommandName == "Authorize")
                {
                    clientId = int.Parse(ClientsDropDownList.SelectedValue);
                    var rc = new ResourceClient()
                    {
                        ResourceID             = resourceId,
                        ClientID               = clientId,
                        AuthLevel              = selectedAuthLevel,
                        Expiration             = null,
                        EmailNotify            = null,
                        PracticeResEmailNotify = null
                    };

                    SetExpiration(rc);

                    DataSession.Insert(rc);
                    ClearResourceClientsCache();

                    var lname    = string.Empty;
                    var fname    = string.Empty;
                    var splitter = ClientsDropDownList.SelectedItem.Text.Split(',');

                    if (splitter.Length > 0)
                    {
                        lname = splitter[0].Trim();
                    }

                    if (splitter.Length > 1)
                    {
                        fname = splitter[1].Trim();
                    }

                    CurrentClients.Add(new ResourceClientItem()
                    {
                        ResourceClientID = rc.ResourceClientID,
                        ClientID         = clientId,
                        AuthLevel        = selectedAuthLevel,
                        LName            = lname,
                        FName            = fname,
                        Expiration       = rc.Expiration,
                        ContactUrl       = GetContactUrl(clientId),
                        AuthDuration     = GetCurrentResource().AuthDuration,
                        Email            = GetEmailAddress(clientId)
                    });
                }
                else if (e.CommandName == "Modify")
                {
                    clientId = int.Parse(ClientIdHiddenField.Value);
                    var cc = CurrentClients.FirstOrDefault(x => x.ClientID == clientId);
                    if (cc != null)
                    {
                        refreshAuthLevel |= cc.AuthLevel;

                        var rc = DataSession.Single <ResourceClient>(cc.ResourceClientID);
                        rc.AuthLevel = selectedAuthLevel;
                        SetExpiration(rc);

                        DataSession.SaveOrUpdate(rc);
                        ClearResourceClientsCache();

                        cc.AuthLevel  = selectedAuthLevel;
                        cc.Expiration = rc.Expiration;

                        CancelEdit();
                    }
                }

                Fill(refreshAuthLevel);
                FillClients();
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex.Message);
            }
        }
Example #24
0
        private void EstablishADWSConnectionUsingDomainConnection(string initialServer, IPAddress[] triedIPAddresses)
        {
            Domain domain = null;

            try
            {
                domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, initialServer));
            }
            catch (ActiveDirectoryObjectNotFoundException ex)
            {
                Trace.WriteLine("Unable to get the domain info");
                Trace.WriteLine("Exception: " + ex.Message);
                Trace.WriteLine("Type: " + ex.GetType().ToString());
                throw;
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Unable to get the domain info");
                Trace.WriteLine("Exception: " + ex.Message);
                Trace.WriteLine("Type: " + ex.GetType().ToString());
            }
            string message = null;

            if (domain == null)
            {
                Trace.WriteLine("Unable to connect to the domain. Trying manually some ip");
                foreach (IPAddress ip in triedIPAddresses)
                {
                    try
                    {
                        Trace.WriteLine("Ip tried: " + ip.ToString());
                        domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.DirectoryServer, ip.ToString()));
                        Trace.WriteLine("OK");
                        break;
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine("Unable to get the domain info");
                        Trace.WriteLine("Exception: " + ex.Message);
                        Trace.WriteLine("Type: " + ex.GetType().ToString());
                        message = ex.Message;
                    }
                }
            }
            if (domain == null)
            {
                throw new EndpointNotFoundException("The program was unable to connect to the server/domain " + initialServer + " to find ADWS server. Check that you have access to this domain. Do not forget that you can enter a specific domain controller in replacement of the domain name. (" + message + ")");
            }

            foreach (DomainController dc in domain.FindAllDomainControllers())
            {
                bool found = false;
                for (int i = 0; i < triedIPAddresses.Length; i++)
                {
                    if (triedIPAddresses[i].ToString() == dc.IPAddress)
                    {
                        found = true;
                        break;
                    }
                }
                if (found)
                {
                    continue;
                }
                try
                {
                    Server = dc.IPAddress;
                    Trace.WriteLine("Trying " + Server);
                    GetDomainInfo();
                    Trace.WriteLine("The connection worked");
                    return;
                }
                catch (EndpointNotFoundException)
                {
                    Trace.WriteLine("The connection didn't worked");
                    CleanConnection <Resource>(_resource);
                    _resource = null;
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Exception: " + ex.Message);
                    Trace.WriteLine("Type: " + ex.GetType().ToString());
                    Trace.WriteLine("The connection didn't worked");
                    CleanConnection <Resource>(_resource);
                    _resource = null;
                }
            }
            Trace.WriteLine("No connection worked");
            throw new EndpointNotFoundException("The connection to ADWS for " + initialServer + " didn't worked. Check that ADWS is installed in at least one server (by default since Windows 2008 R2, manually since Windows 2003) or that the port 9389 is not firewalled. Do not forget that you can enter a specific domain controller as a replacement for the domain name.");
        }
Example #25
0
        public static async Task CreateVmAsync(
            string subscriptionId,
            string resourceGroup,
            string location,
            string vmName)
        {
            // Initialize Client
            var resourceClient = new ResourceClient(subscriptionId, new DefaultAzureCredential(true));
            var networkClient  = new NetworkClient(subscriptionId, new DefaultAzureCredential(true));
            var computeClient  = new ComputeClient(subscriptionId, new DefaultAzureCredential(true));

            // Create Resource Group
            await resourceClient.ResourceGroups.CreateOrUpdateAsync(resourceGroup, new ResourceGroup(location));

            // Create AvailabilitySet
            var availabilitySet = new AvailabilitySet(location)
            {
                PlatformUpdateDomainCount = 5,
                PlatformFaultDomainCount  = 2,
                Sku = new Sku()
                {
                    Name = "Aligned"
                }                                     // TODO. Verify new codegen on AvailabilitySetSkuTypes.Aligned
            };

            availabilitySet = await computeClient.AvailabilitySets
                              .CreateOrUpdateAsync(resourceGroup, vmName + "_aSet", availabilitySet);

            // Create IP Address
            // TODO verify why lack of (location) ctor.
            var ipAddress = new PublicIPAddress()
            {
                PublicIPAddressVersion   = IPVersion.IPv4,
                PublicIPAllocationMethod = IPAllocationMethod.Dynamic,
                Location = location,
            };

            ipAddress = await networkClient
                        .PublicIPAddresses.StartCreateOrUpdate(resourceGroup, vmName + "_ip", ipAddress)
                        .WaitForCompletionAsync();

            // Create VNet
            var vnet = new VirtualNetwork()
            {
                Location     = location,
                AddressSpace = new AddressSpace()
                {
                    AddressPrefixes = new List <string>()
                    {
                        "10.0.0.0/16"
                    }
                },
                Subnets = new List <Subnet>()
                {
                    new Subnet()
                    {
                        Name          = "mySubnet",
                        AddressPrefix = "10.0.0.0/24",
                    }
                },
            };

            vnet = await networkClient.VirtualNetworks
                   .StartCreateOrUpdate(resourceGroup, vmName + "_vent", vnet)
                   .WaitForCompletionAsync();

            // Create Network interface
            var nic = new NetworkInterface()
            {
                Location         = location,
                IpConfigurations = new List <NetworkInterfaceIPConfiguration>()
                {
                    new NetworkInterfaceIPConfiguration()
                    {
                        Name    = "Primary",
                        Primary = true,
                        Subnet  = new Subnet()
                        {
                            Id = vnet.Subnets.First().Id
                        },
                        PrivateIPAllocationMethod = IPAllocationMethod.Dynamic,
                        PublicIPAddress           = new PublicIPAddress()
                        {
                            Id = ipAddress.Id
                        }
                    }
                }
            };

            nic = await networkClient.NetworkInterfaces
                  .StartCreateOrUpdate(resourceGroup, vmName + "_nic", nic)
                  .WaitForCompletionAsync();

            var vm = new VirtualMachine(location)
            {
                NetworkProfile = new NetworkProfile {
                    NetworkInterfaces = new [] { new NetworkInterfaceReference()
                                                 {
                                                     Id = nic.Id
                                                 } }
                },
                OsProfile = new OSProfile
                {
                    ComputerName       = "testVM",
                    AdminUsername      = "******",
                    AdminPassword      = "******",
                    LinuxConfiguration = new LinuxConfiguration {
                        DisablePasswordAuthentication = false, ProvisionVMAgent = true
                    }
                },
                StorageProfile = new StorageProfile()
                {
                    ImageReference = new ImageReference()
                    {
                        Offer     = "UbuntuServer",
                        Publisher = "Canonical",
                        Sku       = "18.04-LTS",
                        Version   = "latest"
                    },
                    DataDisks = new List <DataDisk>()
                },
                HardwareProfile = new HardwareProfile()
                {
                    VmSize = VirtualMachineSizeTypes.StandardB1Ms
                },
            };

            vm.AvailabilitySet.Id = availabilitySet.Id;

            await computeClient.VirtualMachines
            .StartCreateOrUpdate(resourceGroup, vmName, vm)
            .WaitForCompletionAsync();
        }