コード例 #1
0
    protected void btnIssue_Click(object sender, EventArgs e)
    {
        X509Certificate2 userCertificate = null;

        //
        // Impersonate the caller and read the client certificate from the
        // caller's Personal certificate store.
        //
        WindowsPrincipal wp = Thread.CurrentPrincipal as WindowsPrincipal;
        WindowsIdentity  wi = wp.Identity as WindowsIdentity;

        using (WindowsImpersonationContext wctxt = wi.Impersonate())
        {
            userCertificate = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.CurrentUser, "CN=bobclient");
        }

        X509Certificate2 signingCertificate = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=localhost");

        //
        // The WS-Identity schema requires cards to be signed using SHA-1.
        //
        X509SigningCredentials signingCredentials = new X509SigningCredentials(signingCertificate, SecurityAlgorithms.RsaSha1Signature, SecurityAlgorithms.Sha1Digest);

        //
        // Create an InformationCard
        //
        InformationCard card = new InformationCard(signingCredentials, CustomSecurityTokenServiceConfiguration.StsIssuerAddress);

        card.CardImage   = new CardImage(Context.Request.PhysicalApplicationPath + @"\information-card.png");
        card.CardName    = "AuthAssuranceSTS Managed Card";
        card.TimeExpires = card.TimeIssued.Value + TimeSpan.FromDays(7.0);   // one week
        card.Language    = "en-us";
        TokenServiceEndpoint tokenServiceEndpoint = new TokenServiceEndpoint(X509CardStsHostFactory.StsEndpointAddress,
                                                                             X509CardStsHostFactory.StsMexAddress,
                                                                             UserCredentialType.X509V3Credential,
                                                                             signingCertificate);

        card.TokenServiceList.Add(new TokenService(tokenServiceEndpoint,
                                                   new X509CertificateCredential(userCertificate)));

        List <string> claimTypes = new List <string>();

        claimTypes.Add(ClaimTypes.Name);
        claimTypes.Add(ClaimTypes.DateOfBirth);
        claimTypes.Add(ClaimTypes.AuthenticationMethod);
        claimTypes.Add(ClaimTypes.PostalCode);
        claimTypes.Add(ClaimTypes.MobilePhone);

        card.SupportedClaimTypeList.AddRange(GetDisplayClaimsFromClaimTypes(claimTypes));

        //
        // This card can be used to request a SAML 1.1 token.
        //
        card.SupportedTokenTypeList.Add(Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml11TokenProfile11);

        //
        // This writes the card out in XML as a .CRD file into the HTTP response.
        // Internet Explorer will recognize the MIME type and prompt the user.
        //
        InformationCardSerializer serializer = new InformationCardSerializer();

        Response.ClearContent();
        Response.AddHeader("Content-Disposition", "attachment; filename=InformationCard.crd");
        Response.ContentType = "application/x-informationcardfile";
        serializer.WriteCard(Response.OutputStream, card);
        Response.End();
    }
コード例 #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <Saml2Configuration>(Configuration.GetSection("Saml2"));
            services.Configure <Saml2Configuration>(saml2Configuration =>
            {
                saml2Configuration.SignAuthnRequest   = true;
                saml2Configuration.SigningCertificate = saml2Configuration.DecryptionCertificate = CertificateUtil.Load(AppEnvironment.MapToPhysicalFilePath(Configuration["Saml2:SigningCertificateFile"]), Configuration["Saml2:SigningCertificatePassword"]);

                saml2Configuration.AllowedAudienceUris.Add(saml2Configuration.Issuer);

                var entityDescriptor = new EntityDescriptor();
                entityDescriptor.ReadIdPSsoDescriptorFromFile(AppEnvironment.MapToPhysicalFilePath(Configuration["Saml2:IdPMetadataFile"]));
                if (entityDescriptor.IdPSsoDescriptor != null)
                {
                    saml2Configuration.AllowedIssuer           = entityDescriptor.EntityId;
                    saml2Configuration.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
                    saml2Configuration.SingleLogoutDestination = entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.First().Location;
                    saml2Configuration.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
                    if (entityDescriptor.IdPSsoDescriptor.WantAuthnRequestsSigned.HasValue)
                    {
                        saml2Configuration.SignAuthnRequest = entityDescriptor.IdPSsoDescriptor.WantAuthnRequestsSigned.Value;
                    }
                }
                else
                {
                    throw new Exception("IdPSsoDescriptor not loaded from metadata.");
                }
            });

            services.AddSaml2(slidingExpiration: true);

            services.AddControllersWithViews();
        }
コード例 #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="options"></param>
        /// <param name="logger"></param>
        /// <exception cref="FileNotFoundException">证书文件不存在</exception>
        /// <exception cref="ArgumentException">Json无法解析</exception>
        public CredentialBiz(IOptions <AuthorizationServerOptions> options)
        {
            _options = options.Value;

            #region Signing Credentials

            //证书
            X509Certificate2?cert = CertificateUtil.GetBySubject(_options.SigningCertificateSubject);

            if (cert == null)
            {
                throw new FrameworkException(ErrorCode.JwtSigningCertNotFound, $"Subject:{_options.SigningCertificateSubject}");
            }

            //密钥
            X509SecurityKey securityKey = new X509SecurityKey(cert);


            _signingCredentials = new SigningCredentials(securityKey, _options.SigningAlgorithm.IsNullOrEmpty() ? SecurityAlgorithms.RsaSha256Signature : _options.SigningAlgorithm);

            #endregion

            #region JsonWebKeySet

            RSA           publicKey  = (RSA)securityKey.PublicKey;
            RSAParameters parameters = publicKey.ExportParameters(false);

            IList <JsonWebKey> jsonWebKeys = new List <JsonWebKey> {
                new JsonWebKey {
                    Kty = "RSA",
                    Use = "sig",
                    Kid = securityKey.KeyId,
                    E   = Base64UrlEncoder.Encode(parameters.Exponent),
                    N   = Base64UrlEncoder.Encode(parameters.Modulus)
                }
            };

            string jsonWebKeySetString = SerializeUtil.ToJson(new { Keys = jsonWebKeys });

            _jsonWebKeySet = new JsonWebKeySet(jsonWebKeySetString);

            #endregion

            #region Encryption Credentials
            X509Certificate2?encryptionCert = CertificateUtil.GetBySubject(_options.EncryptingCertificateSubject);

            if (encryptionCert == null)
            {
                throw new FrameworkException(ErrorCode.JwtEncryptionCertNotFound, $"Subject:{_options.EncryptingCertificateSubject}");
            }

            _encryptingCredentials = new X509EncryptingCredentials(encryptionCert);

            #endregion

            #region Decryption Security Key

            _decryptionSecurityKey = new X509SecurityKey(encryptionCert);

            #endregion
        }
 /// <summary>
 /// MySecurityTokenServiceConfiguration constructor.
 /// </summary>
 public MySecurityTokenServiceConfiguration()
     : base(issuerName, new X509SigningCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, SigningCertificateName)))
 {
     this.SecurityTokenService = typeof(MySecurityTokenService);
 }
コード例 #5
0
            public void Start(bool isTls = false, bool doContinuations = false)
            {
                server = SockNetServer.Create(GetLocalIpAddress(), 0, ServerSockNetChannel.DefaultBacklog, pool);

                try
                {
                    server.AddModule(new WebSocketServerSockNetChannelModule("/", "localhost"));

                    if (isTls)
                    {
                        byte[] rawCert = CertificateUtil.CreateSelfSignCertificatePfx("CN=\"test\"; C=\"USA\"", DateTime.Today.AddDays(-10), DateTime.Today.AddDays(+10));

                        server.BindWithTLS(new X509Certificate2(rawCert),
                                           (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return(true); }).WaitForValue(TimeSpan.FromSeconds(5));
                    }
                    else
                    {
                        server.Bind().WaitForValue(TimeSpan.FromSeconds(5));
                    }

                    Assert.IsTrue(server.IsActive);

                    server.Pipe.AddIncomingLast <WebSocketFrame>((ISockNetChannel channel, ref WebSocketFrame data) =>
                    {
                        if (doContinuations)
                        {
                            int perFrameSize = data.Data.Length / 3;

                            for (int i = 0; i < 3; i++)
                            {
                                bool isDone = false;
                                byte[] rawData;

                                if (i + 1 < 3)
                                {
                                    rawData = new byte[perFrameSize];
                                    isDone  = false;
                                }
                                else
                                {
                                    rawData = new byte[data.Data.Length - (perFrameSize * 2)];
                                    isDone  = true;
                                }

                                Buffer.BlockCopy(data.Data, i * perFrameSize, rawData, 0, rawData.Length);

                                if (data.Operation == WebSocketFrame.WebSocketFrameOperation.BinaryFrame)
                                {
                                    channel.Send(WebSocketFrame.CreateBinaryFrame(rawData, true, i != 0, isDone));
                                }
                                else
                                {
                                    channel.Send(WebSocketFrame.CreateTextFrame(rawData, true, i != 0, isDone));
                                }
                            }
                        }
                        else
                        {
                            channel.Send(data);
                        }
                    });
                }
                catch (Exception)
                {
                    Stop();
                }
            }
 public CustomSecurityTokenServiceConfiguration()
     : base(StsIssuerAddress, new X509SigningCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=localhost")))
 {
     SecurityTokenService = typeof(AuthAssuranceSTS.CustomSecurityTokenService);
 }
コード例 #7
0
        public async Task RetrieveAccessToken_Success_TokenInformationIsInResponse()
        {
            var wspCertificate = CertificateUtil.GetCertificate("d9f10c97aa647727adb64a349bb037c5c23c9a7a");

            var accessToken     = "dummy";
            var oioIdwsTokenKey = "accesstoken1";
            var token           = new OioIdwsToken
            {
                Type       = AccessTokenType.Bearer,
                ExpiresUtc = DateTime.UtcNow.AddHours(1),
                Claims     = new[]
                {
                    new OioIdwsClaim
                    {
                        Type      = "type1",
                        Value     = "value1",
                        ValueType = "valuetype1",
                        Issuer    = "issuer1",
                    },
                    new OioIdwsClaim
                    {
                        Type      = "type2",
                        Value     = "value2",
                        ValueType = "valuetype2",
                        Issuer    = "issuer2",
                    },
                }
            };

            var tokenStoreMock = new Mock <ISecurityTokenStore>();

            tokenStoreMock
            .Setup(x => x.RetrieveTokenAsync(oioIdwsTokenKey))
            .ReturnsAsync(token);

            var tokenDataFormatMock = new Mock <ISecureDataFormat <AuthenticationProperties> >();

            tokenDataFormatMock
            .Setup(x => x.Unprotect(accessToken))
            .Returns(new AuthenticationProperties
            {
                ExpiresUtc = DateTimeOffset.UtcNow.AddHours(1),
                Dictionary = { { "value", oioIdwsTokenKey } }
            });

            var options = new OioIdwsAuthorizationServiceOptions
            {
                AccessTokenIssuerPath            = new PathString("/accesstoken/issue"),
                AccessTokenRetrievalPath         = new PathString("/accesstoken"),
                IssuerAudiences                  = () => Task.FromResult(new IssuerAudiences[0]),
                SecurityTokenStore               = tokenStoreMock.Object,
                TokenDataFormat                  = tokenDataFormatMock.Object,
                TrustedWspCertificateThumbprints = new[] { "d9f10c97aa647727adb64a349bb037c5c23c9a7a" },
                CertificateValidator             = X509CertificateValidator.None //no reason for tests to validate certs
            };

            using (var server = TestServerWithClientCertificate.Create(() => wspCertificate, app =>
            {
                app.UseOioIdwsAuthorizationService(options);
            }))
            {
                server.BaseAddress = new Uri("https://localhost/");

                var response = await server.HttpClient.GetAsync($"/accesstoken?{accessToken}");

                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                Assert.AreEqual("application/json", response.Content.Headers.ContentType.MediaType);
                var responseToken = JsonConvert.DeserializeObject <OioIdwsToken>(await response.Content.ReadAsStringAsync());

                Assert.AreEqual(token.Type, responseToken.Type);
                Assert.AreEqual(token.ExpiresUtc, responseToken.ExpiresUtc);
                Assert.AreEqual(token.Claims.Count, responseToken.Claims.Count);
                Assert.AreEqual(token.Claims.ElementAt(0).Type, responseToken.Claims.ElementAt(0).Type);
                Assert.AreEqual(token.Claims.ElementAt(0).Value, responseToken.Claims.ElementAt(0).Value);
            }
        }
コード例 #8
0
        static void Main(string[] args)
        {
            WSTrustServiceHost stsHost = null;

            try
            {
                SecurityTokenServiceConfiguration stsConfiguration = new SecurityTokenServiceConfiguration(Address.StsAddress,
                                                                                                           new X509SigningCredentials(
                                                                                                               CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine,
                                                                                                                                              "CN=localhost")));
                stsConfiguration.SecurityTokenService = typeof(CustomSecurityTokenService);

                // Add the STS endpoint information
                stsConfiguration.TrustEndpoints.Add(
                    new ServiceHostEndpointConfiguration(typeof(IWSTrust13SyncContract), new WindowsWSTrustBinding(), Address.StsAddress));

                stsHost = new WSTrustServiceHost(stsConfiguration, new Uri(Address.StsAddress));
                stsHost.Open();

                Console.WriteLine("The security token service has started at {0}.\n", Address.StsAddress);
                Console.WriteLine("Press [Enter] to stop.\n");
                Console.ReadLine();
            }
            finally
            {
                try
                {
                    if (stsHost != null)
                    {
                        stsHost.Close();
                    }
                }
                catch (CommunicationException)
                {
                }
                catch (TimeoutException)
                {
                }
            }
        }
コード例 #9
0
        public async Task RetrieveAccessToken_ExpiredAccessToken_ReturnsUnauthorized()
        {
            var wspCertificate = CertificateUtil.GetCertificate("d9f10c97aa647727adb64a349bb037c5c23c9a7a");

            var accessToken     = "accessToken1";
            var oioIdwsTokenKey = "tokenValue1";

            var tokenInformation = new OioIdwsToken();

            var authProperties = new AuthenticationProperties
            {
                Dictionary = { { "value", oioIdwsTokenKey } }
            };

            var tokenDataFormatMock = new Mock <ISecureDataFormat <AuthenticationProperties> >();

            tokenDataFormatMock
            .Setup(x => x.Unprotect(accessToken))
            .Returns(() => authProperties);

            var currentTime = DateTimeOffset.UtcNow; //ensure static time during test

            var timeMock = new Mock <ISystemClock>();

            // ReSharper disable once AccessToModifiedClosure
            timeMock
            .SetupGet(x => x.UtcNow)
            .Returns(() => currentTime);

            var storeMock = new Mock <ISecurityTokenStore>();

            storeMock
            .Setup(x => x.RetrieveTokenAsync(oioIdwsTokenKey))
            .Returns(() => Task.FromResult(tokenInformation));

            var options = new OioIdwsAuthorizationServiceOptions
            {
                AccessTokenIssuerPath            = new PathString("/accesstoken/issue"),
                AccessTokenRetrievalPath         = new PathString("/accesstoken"),
                IssuerAudiences                  = () => Task.FromResult(new IssuerAudiences[0]),
                TrustedWspCertificateThumbprints = new[] { "d9f10c97aa647727adb64a349bb037c5c23c9a7a" },
                CertificateValidator             = X509CertificateValidator.None, //no reason for tests to validate certs
                TokenDataFormat                  = tokenDataFormatMock.Object,
                SystemClock        = timeMock.Object,
                MaxClockSkew       = TimeSpan.FromMinutes(5),
                SecurityTokenStore = storeMock.Object,
            };

            using (var server = TestServerWithClientCertificate.Create(() => wspCertificate, app =>
            {
                app.UseOioIdwsAuthorizationService(options);
            }))
            {
                server.BaseAddress = new Uri("https://localhost/");

                {
                    //test that token content is checked properly
                    authProperties.ExpiresUtc = currentTime - options.MaxClockSkew.Add(TimeSpan.FromSeconds(1));

                    var response = await server.HttpClient.GetAsync($"/accesstoken?{accessToken}");

                    Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
                    var json = JObject.Parse(await response.Content.ReadAsStringAsync());
                    Assert.AreEqual(1, json["expired"].Value <int>());
                }

                {
                    //test that stored token information is checked properly
                    authProperties.ExpiresUtc   = currentTime;
                    tokenInformation.ExpiresUtc = currentTime - options.MaxClockSkew.Add(TimeSpan.FromSeconds(1));

                    var response = await server.HttpClient.GetAsync($"/accesstoken?{accessToken}");

                    Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
                    var json = JObject.Parse(await response.Content.ReadAsStringAsync());
                    Assert.AreEqual(1, json["expired"].Value <int>());
                }
            }
        }
コード例 #10
0
        public async Task <ActionResult> AssertionConsumerService()
        {
            var binding            = new Saml2PostBinding();
            var saml2AuthnResponse = new Saml2AuthnResponse();

            binding.Unbind(Request, saml2AuthnResponse, CertificateUtil.Load(Constants.ConfigSettings.SAX509Certificate));

            SAAuthenticationResponse claims;

            try
            {
                claims = DecodeAuthnResponse(saml2AuthnResponse);
            }
            catch (Exception e)
            {
                AppGlobal.Log.WriteLog(String.Format("Secure Access - Decoding AuthnResponse failed due to {0}.",
                                                     e.InnerException));
                ViewBag.MessageHtml = AppGlobal.Language.GetText(this, "SSOLogInFailed",
                                                                 "Log in failed for DfE Secure Access. If you believe you should have access to the Post 16 Provider Portal please contact the DfE Support Team on <a href='tel:08448115028'>0844 8115 028</a> or <a href='mailto:[email protected]'>[email protected]</a>.");
                ViewBag.ButtonText = AppGlobal.Language.GetText(this, "BackToSecureAccessButton",
                                                                "Back to Secure Access");
                ViewBag.ButtonUrl = Constants.ConfigSettings.SAHomePage;
                return(View("Info"));
            }

            if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                AuthenticationManager.SignOut();
                SessionManager.End();
            }

            UserResponse userResult = await GetUserAsync(claims);

            if (!String.IsNullOrEmpty(userResult.Message))
            {
                ViewBag.MessageHtml = userResult.Message;
                ViewBag.MessageHtml = userResult.Message;
                ViewBag.ButtonText  = AppGlobal.Language.GetText(this, "BackToSecureAccessButton",
                                                                 "Back to Secure Access");
                ViewBag.ButtonUrl = Constants.ConfigSettings.SAHomePage;
                return(View("Info"));
            }

            ProviderResponse providerResult = await GetValidatedProviderAsync(claims, userResult.User.Id);

            if (!String.IsNullOrEmpty(providerResult.Message))
            {
                ViewBag.MessageHtml = providerResult.Message;
                ViewBag.ButtonText  = AppGlobal.Language.GetText(this, "BackToSecureAccessButton",
                                                                 "Back to Secure Access");
                ViewBag.ButtonUrl = Constants.ConfigSettings.SAHomePage;
                return(View("Info"));
            }

            // Associate user with the provider
            if (!userResult.User.Providers2.Any() ||
                userResult.User.Providers2.All(x => x.ProviderId != providerResult.Provider.ProviderId))
            {
                userResult.User.Providers2.Clear();
                userResult.User.Providers2.Add(providerResult.Provider);
            }
            userResult.User.LastLoginDateTimeUtc = DateTime.UtcNow;
            await db.SaveChangesAsync();

            // Actually log them in
            ApplicationUser user = await UserManager.FindByIdAsync(userResult.User.Id);

            await SignInManager.SignInAsync(user, true, false);

            // If we are doing a SAML2 log out we need to store this information for later use.
            // Set some extra properties so we can log out later
            //CacheManagement.CacheHandler.Add("SAML2Claims:" + aspNetUser.Id, new List<Claim>
            //{
            //    new Claim(Saml2ClaimTypes.NameId, claims.NameId),
            //    new Claim(Saml2ClaimTypes.NameIdFormat, claims.NameIdFormat),
            //    new Claim(Saml2ClaimTypes.SessionIndex, claims.SessionIndex),
            //});

            SessionManager.Start();

            // Bounce them via the following page so that their session is instantiated correctly
            string returnUrl = binding.GetRelayStateQuery()[RelayStateReturnUrl];

            return(RedirectToAction("LogInComplete", new { returnUrl }));
        }
コード例 #11
0
        static async Task MainAsync(string[] args)
        {
            Clear();
            WriteLine("Available transport types:");
            WriteLine("1 - TcpTransport (default)");
            WriteLine("2 - PipeTcpTransport");
            WriteLine("3 - WebSocketTransport");
            WriteLine("4 - PipeWebSocketTransport");

            Write("Select type: ");
            if (!int.TryParse(ReadLine(), out var transportType))
            {
                transportType = 1;
            }

            Func <ITransportListener> transportListenerFactory;
            Func <ITransport>         clientTransportFactory;
            Uri uri;
            var envelopeSerializer = new EnvelopeSerializer(new DocumentTypeResolver());
            RemoteCertificateValidationCallback certificateValidationCallback = (sender, certificate, chain, errors) => true;


            var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

            switch (transportType)
            {
            case 2:
                uri = new Uri(configuration["PipeTcpTransport"]);
                transportListenerFactory = () =>
                                           new PipeTcpTransportListener(
                    uri,
                    CertificateUtil.CreateSelfSignedCertificate("localhost"),
                    new EnvelopeSerializer(new DocumentTypeResolver()),
                    clientCertificateValidationCallback: certificateValidationCallback);
                clientTransportFactory = () => new PipeTcpTransport(envelopeSerializer, serverCertificateValidationCallback: certificateValidationCallback);
                break;

            case 3:
                uri = new Uri(configuration["WebSocketTransport"]);
                transportListenerFactory = () =>
                                           new WebSocketTransportListener(
                    new[] { uri },
                    envelopeSerializer,
                    CertificateUtil.CreateSelfSignedCertificate("localhost"),
                    clientCertificateValidationCallback: (clientCertificate, chain, sslPolicyErrors) => certificateValidationCallback(null, clientCertificate, chain, sslPolicyErrors),
                    closeGracefully: false);
                clientTransportFactory = () => new ClientWebSocketTransport(envelopeSerializer, serverCertificateValidationCallback: certificateValidationCallback, closeGracefully: false);
                break;

            case 4:
                uri = new Uri(configuration["PipeWebSocketTransport"]);
                transportListenerFactory = () =>
                                           new PipeWebSocketTransportListener(
                    new[] { uri },
                    envelopeSerializer,
                    CertificateUtil.CreateSelfSignedCertificate("localhost"),
                    clientCertificateValidationCallback: (clientCertificate, chain, sslPolicyErrors) => certificateValidationCallback(null, clientCertificate, chain, sslPolicyErrors),
                    closeGracefully: false);
                clientTransportFactory = () => new PipeClientWebSocketTransport(envelopeSerializer, serverCertificateValidationCallback: certificateValidationCallback, closeGracefully: false);
                break;

            default:
                uri = new Uri(configuration["TcpTransport"]);
                transportListenerFactory = () =>
                                           new TcpTransportListener(
                    uri,
                    CertificateUtil.CreateSelfSignedCertificate("localhost"),
                    envelopeSerializer,
                    clientCertificateValidationCallback: certificateValidationCallback);
                clientTransportFactory = () => new TcpTransport(envelopeSerializer, serverCertificateValidationCallback: certificateValidationCallback);
                break;
            }

            WriteLine("Starting the server...");

            var actionBlockOptions = new ExecutionDataflowBlockOptions
            {
                BoundedCapacity        = DataflowBlockOptions.Unbounded,
                MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded,
                EnsureOrdered          = false
            };

            var reportActionBlock = new ActionBlock <Envelope>(
                m => _reporter?.ReportEvent(),
                actionBlockOptions);


            var server = new ServerBuilder("[email protected]/default", transportListenerFactory())
                         .WithChannelConsumers(
                m => reportActionBlock.SendAsync(m),
                n => reportActionBlock.SendAsync(n),
                c => reportActionBlock.SendAsync(c))
                         .WithEnabledEncryptionOptions(new SessionEncryption[] { SessionEncryption.None, SessionEncryption.TLS })
                         .WithExceptionHandler(e =>
            {
                var cursorTop   = CursorTop;
                CursorTop       = 20;
                ForegroundColor = ConsoleColor.Red;
                WriteLine(e.ToString());
                ResetColor();
                CursorTop = cursorTop;
                return(TaskUtil.TrueCompletedTask);
            })
                         .WithEnvelopeBufferSize(-1)
                         .Build();

            await server.StartAsync(CancellationToken.None);

            WriteLine("Server started.");

            var cursorLeft = CursorLeft;
            var cursorTop  = CursorTop;

            while (true)
            {
                CursorLeft = cursorLeft;
                CursorTop  = cursorTop;
                WriteLine("                                                            ");
                WriteLine("                                                            ");
                WriteLine("                                                            ");
                WriteLine("                                                            ");
                WriteLine("                                                            ");
                WriteLine("                                                            ");
                WriteLine("                                                            ");
                WriteLine("                                                            ");
                WriteLine("                                                            ");
                WriteLine("                                                            ");
                CursorLeft = cursorLeft;
                CursorTop  = cursorTop;

                Write("Number of channels (ENTER for 1, EXIT to quit): ");

                var line = ReadLine();
                if (line != null && line.ToLowerInvariant().Equals("exit"))
                {
                    break;
                }

                if (!uint.TryParse(line, out var channelCount))
                {
                    channelCount = 1;
                }

                Write("Envelope buffer size (ENTER for 1): ");
                if (!int.TryParse(ReadLine(), out var envelopeBufferSize))
                {
                    envelopeBufferSize = 1;
                }

                Write("Module delay (ENTER for 0): ");
                if (!uint.TryParse(ReadLine(), out var moduleDelay))
                {
                    moduleDelay = 0;
                }

                WriteLine("Starting the client...");

                var delayMessageChannelModule = new ChannelModule <Message>(
                    async(message, token) =>
                {
                    await Task.Delay((int)moduleDelay, token);
                    return(message);
                },
                    async(message, token) =>
                {
                    await Task.Delay((int)moduleDelay, token);
                    return(message);
                },
                    state => { });

                var channelBuilder = ClientChannelBuilder
                                     .Create(clientTransportFactory, uri)
                                     .WithEnvelopeBufferSize(envelopeBufferSize)
                                     .CreateEstablishedClientChannelBuilder()
                                     .AddEstablishedHandler((channel, token) =>
                {
                    if (moduleDelay > 0)
                    {
                        channel.MessageModules.Add(delayMessageChannelModule);
                    }
                    return(Task.CompletedTask);
                })
                                     .WithEncryption(SessionEncryption.TLS);

                IEstablishedChannel client;

                if (channelCount > 1)
                {
                    client = new MultiplexerClientChannel(channelBuilder);
                    await((MultiplexerClientChannel)client).EstablishAsync(CancellationToken.None);
                }
                else
                {
                    client = await channelBuilder.BuildAndEstablishAsync(CancellationToken.None);
                }

                WriteLine("Client started.");

                Write("Number of tasks (ENTER for 10): ");
                if (!uint.TryParse(ReadLine(), out var taskCount))
                {
                    taskCount = 10;
                }

                Write("Number of messages (ENTER for 1000): ");
                if (!uint.TryParse(ReadLine(), out var messagesCount))
                {
                    messagesCount = 1000;
                }

                Write("Number of notifications (ENTER for 1000): ");
                if (!uint.TryParse(ReadLine(), out var notificationsCount))
                {
                    notificationsCount = 1000;
                }

                Write("Number of commands (ENTER for 1000): ");
                if (!uint.TryParse(ReadLine(), out var commandsCount))
                {
                    commandsCount = 1000;
                }

                _reporter = new Reporter(
                    (int)(taskCount * (messagesCount + notificationsCount + commandsCount)),
                    CursorTop + 2,
                    $"Transp {transportType} Ch {channelCount} Buf {envelopeBufferSize} Delay {moduleDelay} Tasks {taskCount} Msgs {messagesCount} Not {notificationsCount} Cmds {commandsCount}");

                var to      = Node.Parse("name@domain/instance");
                var limeUri = new LimeUri("/ping");

                await Task.WhenAll(
                    Enumerable
                    .Range(0, (int)taskCount)
                    .Select(i => Task.Run(async() =>
                {
                    var messagesTask = Task.Run(async() =>
                    {
                        for (int j = 0; j < messagesCount; j++)
                        {
                            await client.SendMessageAsync(
                                new Message()
                            {
                                Id      = $"{i}_{j}",
                                To      = to,
                                Content = "Testing a message"
                            },
                                CancellationToken.None);
                        }
                    });

                    var notificationsTask = Task.Run(async() =>
                    {
                        for (int j = 0; j < notificationsCount; j++)
                        {
                            await client.SendNotificationAsync(
                                new Notification()
                            {
                                Id    = $"{i}_{j}",
                                To    = to,
                                Event = Event.Received
                            },
                                CancellationToken.None);
                        }
                    });

                    var commandsTask = Task.Run(async() =>
                    {
                        for (int j = 0; j < commandsCount; j++)
                        {
                            await client.SendCommandAsync(
                                new Command()
                            {
                                Id     = $"{i}_{j}",
                                To     = to,
                                Method = CommandMethod.Observe,
                                Uri    = limeUri
                            },
                                CancellationToken.None);
                        }
                    });

                    await Task.WhenAll(messagesTask, notificationsTask, commandsTask);
                })));

                _reporter.ReportSendComplete();
                await _reporter.ReportTask;
                _reporter = null;

                using var finishCts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

                if (client is IOnDemandClientChannel onDemandClientChannel)
                {
                    await onDemandClientChannel.FinishAsync(finishCts.Token);
                }
                else if (client is IClientChannel clientChannel)
                {
                    await clientChannel.SendFinishingSessionAsync(finishCts.Token);

                    await clientChannel.ReceiveFinishedSessionAsync(finishCts.Token);
                }

                client.DisposeIfDisposable();
            }

            using var stopCts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

            await server.StopAsync(stopCts.Token);

            WriteLine("Server stopped. Press ENTER to exit.");
            ReadLine();
        }
コード例 #12
0
        public static void Start()
        {
            try
            {
                var host       = Plugin.LyncPlugin.Configuration.GetString("host");
                var thumbprint = Plugin.LyncPlugin.Configuration.GetString("thumbprint");
                var gruu       = Plugin.LyncPlugin.Configuration.GetString("gruu");
                var trustPort  = Plugin.LyncPlugin.Configuration.GetInt("trustedPort");
                var appPort    = Plugin.LyncPlugin.Configuration.GetInt("appPort");
                var sip        = Plugin.LyncPlugin.Configuration.GetString("accountSip");

                var platformSettings = new ServerPlatformSettings(UserAgent, host, trustPort, gruu, CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, thumbprint));

                Platform    = new CollaborationPlatform(platformSettings);
                AppEndpoint = new ApplicationEndpoint(Platform, new ApplicationEndpointSettings(sip, host, appPort)
                {
                    UseRegistration = true
                });

                Log("Starting Lync platform.");
                Platform.EndStartup(Platform.BeginStartup(null, null));
                Log("Lync platform started.");

                AppEndpoint.EndEstablish(AppEndpoint.BeginEstablish(null, null));

                UserEndpoint = new UserEndpoint(Platform, new UserEndpointSettings(sip, host, appPort)
                {
                    AutomaticPresencePublicationEnabled = true
                });
                UserEndpoint.EndEstablish(UserEndpoint.BeginEstablish(null, null));

                RemotePresence = new RemotePresenceView(UserEndpoint, new RemotePresenceViewSettings());
                RemotePresence.PresenceNotificationReceived += PresenceNotificationReceived;
            }
            catch (Exception ex)
            {
                Error(ex.Message);
            }
        }
コード例 #13
0
            public void Start(bool isTls = false)
            {
                string sampleContent = "<test><val>hello</val></test>";

                int sampleContentLength = Encoding.UTF8.GetByteCount(sampleContent);

                string chunk1Content = "<test><val>";
                string chunk2Content = "hello</val>";
                string chunk3Content = "</test>";

                int chunk1ContentLength = Encoding.UTF8.GetByteCount(chunk1Content);
                int chunk2ContentLength = Encoding.UTF8.GetByteCount(chunk2Content);
                int chunk3ContentLength = Encoding.UTF8.GetByteCount(chunk3Content);

                string chunk1HttpContent = "HTTP/1.0 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + string.Format("{0:X}", chunk1ContentLength) + "\r\n" + chunk1Content + "\r\n";
                string chunk2HttpContent = string.Format("{0:X}", chunk2ContentLength) + "\r\n" + chunk2Content + "\r\n";
                string chunk3HttpContent = string.Format("{0:X}", chunk3ContentLength) + "\r\n" + chunk3Content + "\r\n";
                string chunk4HttpContent = "0\r\n\r\n";

                server = SockNetServer.Create(GetLocalIpAddress(), 0, ServerSockNetChannel.DefaultBacklog, pool);

                try
                {
                    server.AddModule(new HttpSockNetChannelModule(HttpSockNetChannelModule.ParsingMode.Server));

                    server.Pipe.AddIncomingLast <HttpRequest>((ISockNetChannel channel, ref HttpRequest data) =>
                    {
                        ChunkedBuffer buffer1 = new ChunkedBuffer(channel.BufferPool);
                        buffer1.Write(Encoding.ASCII.GetBytes(chunk1HttpContent), 0, Encoding.ASCII.GetByteCount(chunk1HttpContent));
                        channel.Send(buffer1);

                        ChunkedBuffer buffer2 = new ChunkedBuffer(channel.BufferPool);
                        buffer2.Write(Encoding.ASCII.GetBytes(chunk2HttpContent), 0, Encoding.ASCII.GetByteCount(chunk2HttpContent));
                        channel.Send(buffer2);

                        ChunkedBuffer buffer3 = new ChunkedBuffer(channel.BufferPool);
                        buffer3.Write(Encoding.ASCII.GetBytes(chunk3HttpContent), 0, Encoding.ASCII.GetByteCount(chunk3HttpContent));
                        channel.Send(buffer3);

                        ChunkedBuffer buffer4 = new ChunkedBuffer(channel.BufferPool);
                        buffer4.Write(Encoding.ASCII.GetBytes(chunk4HttpContent), 0, Encoding.ASCII.GetByteCount(chunk4HttpContent));
                        channel.Send(buffer4);
                    });

                    if (isTls)
                    {
                        byte[] rawCert = CertificateUtil.CreateSelfSignCertificatePfx("CN=\"test\"; C=\"USA\"", DateTime.Today.AddDays(-10), DateTime.Today.AddDays(+10));

                        server.BindWithTLS(new X509Certificate2(rawCert),
                                           (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return(true); }).WaitForValue(TimeSpan.FromSeconds(5));
                    }
                    else
                    {
                        server.Bind().WaitForValue(TimeSpan.FromSeconds(5));
                    }

                    Assert.IsTrue(server.IsActive);
                }
                catch (Exception)
                {
                    Stop();
                }
            }