Ejemplo n.º 1
0
        public async Task CallWspService_Authenticates_ReturnsUserInformation()
        {
            var serverEndpoint = "https://digst.oioidws.rest.wsp:10002";

            var wspServer = WebApp.Start(serverEndpoint, app =>
            {
                app.SetLoggerFactory(new ConsoleLoggerFactory());

                app
                .UseOioIdwsAuthentication(new OioIdwsAuthenticationOptions())
                .UseOioIdwsAuthorizationService(new OioIdwsAuthorizationServiceOptions
                {
                    AccessTokenIssuerPath = new PathString("/accesstoken/issue"),
                    IssuerAudiences       = () => Task.FromResult(new[]
                    {
                        new IssuerAudiences("d9f10c97aa647727adb64a349bb037c5c23c9a7a", "test cert")
                        .Audience(new Uri("https://wsp.oioidws-net.dk")),
                    }),
                })
                .Use(async(context, next) =>
                {
                    var identity = (ClaimsIdentity)context.Request.User.Identity;
                    await context.Response.WriteAsync(identity.Claims
                                                      .Single(x => x.Type == "dk:gov:saml:attribute:CvrNumberIdentifier").Value);
                });
            });
            {
                var settings = new OioIdwsClientSettings
                {
                    ClientCertificate         = CertificateUtil.GetCertificate("0E6DBCC6EFAAFF72E3F3D824E536381B26DEECF5"),
                    AudienceUri               = new Uri("https://wsp.oioidws-net.dk"),
                    AccessTokenIssuerEndpoint = new Uri(serverEndpoint + "/accesstoken/issue"),
                    SecurityTokenService      = new OioIdwsStsSettings
                    {
                        Certificate     = CertificateUtil.GetCertificate("d9f10c97aa647727adb64a349bb037c5c23c9a7a"),
                        EndpointAddress = new Uri("https://SecureTokenService.test-nemlog-in.dk/SecurityTokenService.svc"),
                        TokenLifeTime   = TimeSpan.FromMinutes(5)
                    },
                    DesiredAccessTokenExpiry = TimeSpan.FromMinutes(5),
                    UseTokenCache            = false
                };

                var idwsClient = new OioIdwsClient(settings);

                var httpClient = new HttpClient(idwsClient.CreateMessageHandler())
                {
                    BaseAddress = new Uri(serverEndpoint)
                };

                var response = await httpClient.GetAsync("/myservice");

                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                var str = await response.Content.ReadAsStringAsync();

                Assert.AreEqual("34051178", str);

                wspServer.Dispose();
            }
        }
 public AccessTokenServiceCache(OioIdwsClient client)
 {
     if (client == null)
     {
         throw new ArgumentNullException(nameof(client));
     }
     _client         = client;
     _tokenService   = new AccessTokenService(_client.Settings);
     _cacheClockSkew = _client.Settings.CacheClockSkew;
 }
Ejemplo n.º 3
0
        public void Test1()
        {
            CryptoConfig.AddAlgorithm(typeof(RsaPkcs1Sha256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");

            var stsSettings = new OioIdwsStsSettings
            {
                Certificate     = SEI2Certificates.GetCertificate(SEI2Certificates.STS),
                SendTimeout     = TimeSpan.FromDays(1.0),
                EndpointAddress = new Uri("https://securetokenservice.test-nemlog-in.dk/SecurityTokenService.svc"),
                TokenLifeTime   = TimeSpan.FromDays(5.0),
            };

            var certificate    = SEI2Certificates.GetCertificate(SEI2Certificates.XMedicus_Systems_ApS_IDWS_Test);
            var clientSettings = new OioIdwsClientSettings
            {
                ClientCertificate         = certificate,
                SecurityTokenService      = stsSettings,
                AudienceUri               = new Uri("https://wsp.oioidws-net.dk"), //"https://wsc.test.xmedicus.com"),
                AccessTokenIssuerEndpoint = new Uri("https://seiidws.test.sundhedsdatastyrelsen.dk"),
            };

            var client = new OioIdwsClient(clientSettings);

            var token = client.GetSecurityToken();

            var abort = new SEI2SchemaAbortionContract();

            abort.schemaCreatedDate = DateTime.Now;
            abort.schemaUserGroupId = "GRP-0000117";
            abort.city             = "København";
            abort.country          = "5100";
            abort.firstName        = "Nancy";
            abort.gender           = SEI2Gender.Female;
            abort.municipalityCode = "147";
            abort.paymentCode      = SEI2PaymentCode.PaidByCounty;
            abort.noReference      = NoYes.No;
            abort.referenceDate    = DateTime.Now;
            abort.sORCode          = "223423423423";
            abort.schemaPersonCivilRegistrationIdentifier = "121212-1212";
            abort.streetName = "Test";
            abort.streetNum  = "246";
            abort.surName    = "Berggren";
            abort.zipCode    = "2860";

            var res = SEI2Helper.Submit(abort, "report", token);

            Console.WriteLine(res);

            Assert.True(res != null);
        }
Ejemplo n.º 4
0
        public static async Task Go()
        {
            //configures the internal logger for OIO WS-TRUST communication
            LoggerFactory.SetLogger(new ConsoleLogger());

            var settings = new OioIdwsClientSettings
            {
                ClientCertificate         = CertificateUtil.GetCertificate(ConfigurationManager.AppSettings["ClientCertificate"]),
                AudienceUri               = new Uri(ConfigurationManager.AppSettings["AudienceUri"]),
                AccessTokenIssuerEndpoint = new Uri(ConfigurationManager.AppSettings["AsEndpoint"]),
                SecurityTokenService      = new OioIdwsStsSettings
                {
                    Certificate     = CertificateUtil.GetCertificate(ConfigurationManager.AppSettings["StsCertificate"]),
                    EndpointAddress = new Uri(ConfigurationManager.AppSettings["StsEndpointAddress"]),
                    TokenLifeTime   = TimeSpan.FromSeconds(int.Parse(ConfigurationManager.AppSettings["TokenLifeTimeInSeconds"]))
                }
            };

            var idwsClient = new OioIdwsClient(settings);

            var httpClient = new HttpClient(idwsClient.CreateMessageHandler());

            {
                //first invocation - security token is retrieved and stored in the AS, access token cached by client
                var response = await httpClient.GetAsync(ConfigurationManager.AppSettings["WspTestEndpointAddress"]);

                var responseString = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();

                Console.WriteLine(responseString);
            }

            {
                //second invocation - cached access token is reused
                httpClient = new HttpClient(idwsClient.CreateMessageHandler());
                var wspTestEndpointAddress2 = ConfigurationManager.AppSettings["WspTestEndpointAddress2"];
                if (!string.IsNullOrWhiteSpace(wspTestEndpointAddress2))
                {
                    var response =
                        await httpClient.GetAsync(wspTestEndpointAddress2);

                    var responseString = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();

                    Console.WriteLine(responseString);
                }
            }
        }
Ejemplo n.º 5
0
        public async Task CallWspService_ShortTokenLifeTime_RenegotiatesAccessToken()
        {
            var serverEndpoint = "https://digst.oioidws.rest.wsp:10002";

            var tokensIssuedCount = 0;

            using (WebApp.Start(serverEndpoint, app =>
            {
                app.SetLoggerFactory(new ConsoleLoggerFactory());

                var tokenStore = new InMemorySecurityTokenStore();

                var tokenStoreWrapper = new Mock <ISecurityTokenStore>();
                tokenStoreWrapper
                .Setup(x => x.RetrieveTokenAsync(It.IsAny <string>()))
                .Returns((string accessToken) => tokenStore.RetrieveTokenAsync(accessToken));
                tokenStoreWrapper
                .Setup(x => x.StoreTokenAsync(It.IsAny <string>(), It.IsAny <OioIdwsToken>()))
                .Returns((string accessToken, OioIdwsToken token) =>
                {
                    tokensIssuedCount++;
                    return(tokenStore.StoreTokenAsync(accessToken, token));
                });

                var authorizationServerOptions = new OioIdwsAuthorizationServiceOptions
                {
                    AccessTokenIssuerPath = new PathString("/accesstoken/issue"),
                    IssuerAudiences = () => Task.FromResult(new[]
                    {
                        new IssuerAudiences("d9f10c97aa647727adb64a349bb037c5c23c9a7a", "test cert")
                        .Audience(new Uri("https://wsp.oioidws-net.dk")),
                    }),
                    SecurityTokenStore = tokenStoreWrapper.Object,
                    MaxClockSkew = TimeSpan.FromSeconds(10), //a little time skew is needed for trusting STS tokens
                };

                app
                .UseOioIdwsAuthentication(new OioIdwsAuthenticationOptions())
                .UseOioIdwsAuthorizationService(authorizationServerOptions)
                .Use(async(context, next) =>
                {
                    if (context.Request.User == null)
                    {
                        //we expect the service to REQUIRE authorization
                        context.Response.StatusCode = 401;
                        return;
                    }

                    var identity = (ClaimsIdentity)context.Request.User.Identity;
                    await context.Response.WriteAsync(identity.Claims
                                                      .Single(x => x.Type == "dk:gov:saml:attribute:CvrNumberIdentifier").Value);
                });
            }))
            {
                var settings = new OioIdwsClientSettings
                {
                    ClientCertificate         = CertificateUtil.GetCertificate("0E6DBCC6EFAAFF72E3F3D824E536381B26DEECF5"),
                    AudienceUri               = new Uri("https://wsp.oioidws-net.dk"),
                    AccessTokenIssuerEndpoint = new Uri(serverEndpoint + "/accesstoken/issue"),
                    SecurityTokenService      = new OioIdwsStsSettings
                    {
                        Certificate     = CertificateUtil.GetCertificate("d9f10c97aa647727adb64a349bb037c5c23c9a7a"),
                        EndpointAddress =
                            new Uri("https://SecureTokenService.test-nemlog-in.dk/SecurityTokenService.svc"),
                        TokenLifeTime = TimeSpan.FromMinutes(5)
                    },
                    DesiredAccessTokenExpiry = TimeSpan.FromSeconds(5), //set a very low token expiry time
                };

                var idwsClient = new OioIdwsClient(settings);

                {
                    var handler = (OioIdwsRequestHandler)idwsClient.CreateMessageHandler();

                    var httpClient = new HttpClient(handler)
                    {
                        BaseAddress = new Uri(serverEndpoint)
                    };

                    //first request, token should be valid
                    var response = await httpClient.GetAsync("/myservice");

                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                    var str = await response.Content.ReadAsStringAsync();

                    Assert.AreEqual("34051178", str);
                }

                {
                    var handler = (OioIdwsRequestHandler)idwsClient.CreateMessageHandler();

                    var httpClient = new HttpClient(handler)
                    {
                        BaseAddress = new Uri(serverEndpoint)
                    };

                    Thread.Sleep(TimeSpan.FromSeconds(30));
                    //second request, time has passed, token should be renegotiated
                    var response = await httpClient.GetAsync("/myservice");

                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                    var str = await response.Content.ReadAsStringAsync();

                    Assert.AreEqual("34051178", str);
                }

                Assert.AreEqual(2, tokensIssuedCount);
            }
        }
Ejemplo n.º 6
0
        public static async Task Go()
        {
            Console.WriteLine(
                @"Enter <1> to use seperate test servers for for AS and WSP.
Requires the following examples applications are running:
Digst.OioIdws.Rest.Examples.AS.exe
Digst.OioIdws.Rest.Examples.WSP.exe

Enter <2> to use the combined test server.
Requires the following example application is running:
Digst.OioIdws.Rest.Examples.ServerCombined.exe");
            char c;

            while (!new[] { '1', '2' }.Contains(c = Console.ReadKey().KeyChar))
            {
            }

            string asEndpoint = "https://digst.oioidws.rest.as:10001/accesstoken/issue";

            if (c == '2')
            {
                asEndpoint = "https://digst.oioidws.rest.wsp:10002/accesstoken/issue";
            }

            //configures the internal logger for OIO WS-TRUST communication
            LoggerFactory.SetLogger(new ConsoleLogger());

            var settings = new OioIdwsClientSettings
            {
                ClientCertificate         = CertificateUtil.GetCertificate("0E6DBCC6EFAAFF72E3F3D824E536381B26DEECF5"),
                AudienceUri               = new Uri("https://wsp.oioidws-net.dk"),
                AccessTokenIssuerEndpoint = new Uri(asEndpoint),
                SecurityTokenService      = new OioIdwsStsSettings
                {
                    Certificate     = CertificateUtil.GetCertificate("d9f10c97aa647727adb64a349bb037c5c23c9a7a"),
                    EndpointAddress = new Uri("https://SecureTokenService.test-nemlog-in.dk/SecurityTokenService.svc"),
                }
            };

            var idwsClient = new OioIdwsClient(settings);

            using (var httpClient = new HttpClient(idwsClient.CreateMessageHandler()))
            {
                {
                    //first invocation - security token is retrieved and stored in the AS, access token cached by client
                    var response = await httpClient.GetAsync("https://digst.oioidws.rest.wsp:10002/hello");

                    var responseString = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();

                    Console.WriteLine(responseString);
                }

                {
                    //second invocation - cached access token is reused
                    var response = await httpClient.GetAsync("https://digst.oioidws.rest.wsp:10002/hello2");

                    var responseString = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();

                    Console.WriteLine(responseString);
                }
            }
        }