Example #1
0
        public void NoServerCert()
        {
            StsClient target = new StsClient(new StsBinding(), new EndpointAddress("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"));

            target.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, "c0f554147928c3722670a47be2f92a9089add107");
            target.RequestTicket("Siemens", selfSignedSession, TimeSpan.FromMinutes(10), assertedDefault, requestedDefault);
        }
Example #2
0
        public void NoClientCert()
        {
            StsClient target = new StsClient(new StsBinding(), new EndpointAddress("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"));

            target.ClientCredentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.LocalMachine, StoreName.AddressBook, X509FindType.FindByThumbprint, "23005f9a30f357dfb265de5277db54c5ff61d34d");
            target.RequestTicket("Siemens", selfSignedSession, TimeSpan.FromMinutes(10), assertedDefault, requestedDefault);
        }
Example #3
0
 public void TestInitialize()
 {
     this.config             = new BceClientConfiguration();
     this.config.Credentials = new DefaultBceCredentials(this.ak, this.sk);
     this.config.Endpoint    = this.endpoint;
     this.client             = new StsClient(this.config);
 }
 public void TestInitialize()
 {
     this.config             = new BceClientConfiguration();
     this.config.Credentials =
         new DefaultBceCredentials("d154df3e2ac44e53b566db53ec644a7e", "2e8445d62bc84011991b4306b91f19f8");
     this.config.Endpoint = "http://10.107.37.40:8586";
     this.client          = new StsClient(this.config);
 }
Example #5
0
        public void ConfigViaConfig()
        {
            StsClient  target    = new StsClient("SSIN=79021802145");
            XmlElement assertion = target.RequestTicket("Egelke", session, TimeSpan.FromHours(12), assertedDefault, requestedDefault);

            XmlDocument doc = new XmlDocument();

            doc.ImportNode(assertion, true);
            doc.AppendChild(assertion);
            doc.Save(@"D:\tmp\tst.xml");

            Assert.AreEqual("Assertion", assertion.LocalName);
            Assert.AreEqual("urn:oasis:names:tc:SAML:1.0:assertion", assertion.NamespaceURI);
        }
Example #6
0
        public void ConfigViaCode()
        {
            StsClient target = new StsClient(
                new StsBinding(),
                new EndpointAddress(
                    new Uri("https://services-acpt.ehealth.fgov.be/IAM/Saml11TokenService/v1")
                    , EndpointIdentity.CreateDnsIdentity("*.int.pub.ehealth.fgov.be")
                    )
                );

            //target.Endpoint.Behaviors.Remove<ClientCredentials>();
            //target.Endpoint.Behaviors.Add(new OptClientCredentials());
            target.ClientCredentials.ServiceCertificate.DefaultCertificate = ehSsl; //not really used, but better then the workaround
            target.ClientCredentials.ClientCertificate.Certificate         = auth;
            XmlElement assertion = target.RequestTicket("Anonymous", session, TimeSpan.FromHours(1), assertedDefault, requestedDefault);

            Assert.AreEqual("Assertion", assertion.LocalName);
            Assert.AreEqual("urn:oasis:names:tc:SAML:1.0:assertion", assertion.NamespaceURI);
        }
Example #7
0
        public static string genCredential(Dictionary <string, object> values)
        {
            Credential cred = new Credential {
                SecretId  = (string)values["secretId"],
                SecretKey = (string)values["secretKey"]
            };

            ClientProfile clientProfile = new ClientProfile();
            HttpProfile   httpProfile   = new HttpProfile();

            httpProfile.Endpoint      = ("sts.tencentcloudapi.com");
            clientProfile.HttpProfile = httpProfile;

            string region      = (string)values["region"];
            string bucket      = (string)values["bucket"];
            string allowPrefix = (string)values["allowPrefix"];

            string[] allowActions = (string[])values["allowActions"];
            string   policy       = getPolicy(region, bucket, allowPrefix, allowActions);

            Dictionary <string, object> body = new Dictionary <string, object>();

            body.Add("DurationSeconds", (Int32)values["durationSeconds"]);
            body.Add("Name", "cos-sts-sdk-dotnet");
            body.Add("Policy", policy);

            StsClient client = new StsClient(cred, region, clientProfile);
            GetFederationTokenRequest req = new GetFederationTokenRequest();

            string strParams = JsonConvert.SerializeObject(body);

            req = GetFederationTokenRequest.FromJsonString <GetFederationTokenRequest>(strParams);
            GetFederationTokenResponse resp = client.GetFederationToken(req).
                                              ConfigureAwait(false).GetAwaiter().GetResult();

            return(JsonConvert.SerializeObject(resp));
        }
        /// <summary>
        /// 获取联合身份临时访问凭证
        /// </summary>
        /// <returns></returns>
        public GetFederationTokenResponse GetFederationToken()
        {
            Credential cred = new Credential {
                SecretId  = _cosConfig.SecretId,
                SecretKey = _cosConfig.SecretKey
            };

            ClientProfile clientProfile = new ClientProfile();
            HttpProfile   httpProfile   = new HttpProfile();

            httpProfile.Endpoint      = _cosConfig.EndPoint;
            clientProfile.HttpProfile = httpProfile;

            StsClient client = new StsClient(cred, _cosConfig.Region, clientProfile);
            GetFederationTokenRequest req = new GetFederationTokenRequest();

            req.Name            = _cosConfig.Name;
            req.Policy          = HttpUtility.UrlEncode(_cosConfig.Policy);
            req.DurationSeconds = _cosConfig.DurationSeconds;

            GetFederationTokenResponse resp = client.GetFederationTokenSync(req);

            return(resp);
        }
Example #9
0
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            Collection <XmlElement> reqParams = new Collection <XmlElement>();

            foreach (XmlElement param in tokenRequirement.AdditionalRequestParameters)
            {
                if (param.NamespaceURI == "urn:oasis:names:tc:SAML:1.0:assertion")
                {
                    reqParams.Add(param);
                }
            }

            ISessionCache cache = (ISessionCache)Activator.CreateInstance(clientCredentials.Cache, clientCredentials.Config);

            //Check the cache for existing session.
            String        id;
            List <String> idSort;

            id     = clientCredentials.ClientCertificate.Certificate.Thumbprint + ";";
            id    += clientCredentials.Session.Thumbprint + ";";
            idSort = new List <string>();
            foreach (XmlElement reqParam in reqParams)
            {
                String val;
                val  = "{" + reqParam.GetAttribute("AttributeNamespace") + "}";
                val += reqParam.GetAttribute("AttributeName");
                val += "=";
                val += reqParam.GetElementsByTagName("AttributeValue", "urn:oasis:names:tc:SAML:1.0:assertion")[0].InnerText;
                val += ";";
                idSort.Add(val);
            }
            idSort.Sort();
            foreach (String val in idSort)
            {
                id += val;
            }
            idSort = new List <string>();
            foreach (ClaimTypeRequirement req in tokenRequirement.ClaimTypeRequirements)
            {
                String val = req.ClaimType + ";";
                idSort.Add(val);
            }
            idSort.Sort();
            foreach (String val in idSort)
            {
                id += val;
            }

            XmlNamespaceManager nsmngr       = null;
            DateTime            notOnOrAfter = DateTime.MinValue;

            //Get the value from the cache
            XmlElement assertion = cache.Get(id);

            //If cache had a result, check if it is still valid
            if (assertion != null)
            {
                nsmngr = new XmlNamespaceManager(assertion.OwnerDocument.NameTable);
                nsmngr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

                notOnOrAfter = DateTime.Parse(assertion.SelectSingleNode("saml:Conditions/@NotOnOrAfter", nsmngr).Value, null, DateTimeStyles.RoundtripKind);

                if (notOnOrAfter < DateTime.UtcNow)
                {
                    assertion = null;
                    cache.Remove(id);
                }
            }

            //If the cache wasn't successful, create new.
            if (assertion == null)
            {
                //Get a new assertion token for the session
                StsClient target = new StsClient(tokenRequirement.IssuerBinding, tokenRequirement.IssuerAddress);
                target.Endpoint.Behaviors.Remove <ClientCredentials>();
                target.Endpoint.Behaviors.Add(new OptClientCredentials());
                target.ClientCredentials.ClientCertificate.Certificate = clientCredentials.ClientCertificate.Certificate;
                target.InnerChannel.OperationTimeout = timeout;

                assertion = target.RequestTicket("Anonymous", clientCredentials.Session, clientCredentials.Duration, reqParams, tokenRequirement.ClaimTypeRequirements);

                nsmngr = new XmlNamespaceManager(assertion.OwnerDocument.NameTable);
                nsmngr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

                notOnOrAfter = DateTime.Parse(assertion.SelectSingleNode("saml:Conditions/@NotOnOrAfter", nsmngr).Value, null, DateTimeStyles.RoundtripKind);

                cache.Add(id, assertion, notOnOrAfter);
            }

            //Get some date from the assertion token
            DateTime notBefore   = DateTime.Parse(assertion.SelectSingleNode("saml:Conditions/@NotBefore", nsmngr).Value, null, DateTimeStyles.RoundtripKind);
            String   assertionId = assertion.SelectSingleNode("@AssertionID", nsmngr).Value;

            // Create a KeyIdentifierClause for the SamlSecurityToken
            SamlAssertionKeyIdentifierClause samlKeyIdentifierClause = new SamlAssertionKeyIdentifierClause(assertionId);

            return(new GenericXmlSecurityToken(assertion, new X509SecurityToken(clientCredentials.Session), notBefore, notOnOrAfter, samlKeyIdentifierClause, samlKeyIdentifierClause, null));
        }
Example #10
0
        public void ConfigViaConfig()
        {
            StsClient target = new StsClient("SSIN=79021802145");
            XmlElement assertion = target.RequestTicket("Egelke", session, TimeSpan.FromHours(12), assertedDefault, requestedDefault);

            XmlDocument doc = new XmlDocument();
            doc.ImportNode(assertion, true);
            doc.AppendChild(assertion);
            doc.Save(@"D:\tmp\tst.xml");

            Assert.AreEqual("Assertion", assertion.LocalName);
            Assert.AreEqual("urn:oasis:names:tc:SAML:1.0:assertion", assertion.NamespaceURI);
        }
Example #11
0
        public void ConfigViaCode()
        {
            StsClient target = new StsClient(new StsBinding(), new EndpointAddress("https://www.ehealth.fgov.be/sts_1_1/SecureTokenService"));
            target.Endpoint.Behaviors.Remove<ClientCredentials>();
            target.Endpoint.Behaviors.Add(new OptClientCredentials());
            target.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, "1ac02600f2f2b68f99f1e8eeab2e780470e0ea4c");
            //target.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, "566fd3fe13e3ab185a7224bcec8ad9cffbf9e9c2");
            XmlElement assertion = target.RequestTicket("Anonymous", session, TimeSpan.FromHours(1), assertedDefault, requestedDefault);

            Assert.AreEqual("Assertion", assertion.LocalName);
            Assert.AreEqual("urn:oasis:names:tc:SAML:1.0:assertion", assertion.NamespaceURI);
        }
 public void InvalidAddressHttp404()
 {
     StsClient target = new StsClient(new StsBinding(), new EndpointAddress("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService2"));
     target.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, "c0f554147928c3722670a47be2f92a9089add107");
     target.ClientCredentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.LocalMachine, StoreName.AddressBook, X509FindType.FindByThumbprint, "23005f9a30f357dfb265de5277db54c5ff61d34d");
     target.RequestTicket("Siemens", selfSignedSession, TimeSpan.FromMinutes(10), assertedDefault, requestedDefault);
 }
 public void AllNull()
 {
     StsClient target = new StsClient(new StsBinding(), new EndpointAddress("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"));
     target.RequestTicket(null, null, DateTime.MinValue, DateTime.MaxValue, null, null);
 }
 public void NoServerCert()
 {
     StsClient target = new StsClient(new StsBinding(), new EndpointAddress("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"));
     target.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, "c0f554147928c3722670a47be2f92a9089add107");
     target.RequestTicket("Siemens", selfSignedSession, TimeSpan.FromMinutes(10), assertedDefault, requestedDefault);
 }
        public static Dictionary <string, object> genCredential(Dictionary <string, object> values)
        {
            checkArguments(values, new string[] { "secretId", "secretKey", "region" });

            Credential cred = new Credential {
                SecretId  = (string)values["secretId"],
                SecretKey = (string)values["secretKey"]
            };
            string region = (string)values["region"];

            ClientProfile clientProfile = new ClientProfile();
            HttpProfile   httpProfile   = new HttpProfile();
            String        endpoint      = values.ContainsKey("Domain") ? (string)values["Domain"]:
                                          "sts.tencentcloudapi.com";

            httpProfile.Endpoint      = endpoint;
            clientProfile.HttpProfile = httpProfile;

            // get policy
            string policy = null;

            if (values.ContainsKey("policy"))
            {
                policy = (string)values["policy"];
            }
            if (policy == null)
            {
                checkArguments(values, new string[] { "bucket", "allowActions" });
                string   bucket       = (string)values["bucket"];
                string[] allowActions = (string[])values["allowActions"];
                string[] allowPrefixes;
                if (values.ContainsKey("allowPrefix"))
                {
                    allowPrefixes = new string[] { (string)values["allowPrefix"] };
                }
                else if (values.ContainsKey("allowPrefixes"))
                {
                    allowPrefixes = (string[])values["allowPrefixes"];
                }
                else
                {
                    throw new System.ArgumentException("allowPrefix and allowPrefixes are both null.");
                }
                policy = getPolicy(region, bucket, allowPrefixes, allowActions);
            }

            // duration
            Int32 durationSeconds = 1800;

            if (values.ContainsKey("durationSeconds"))
            {
                durationSeconds = (Int32)values["durationSeconds"];
            }

            Dictionary <string, object> body = new Dictionary <string, object>();

            body.Add("DurationSeconds", durationSeconds);
            body.Add("Name", "cos-sts-sdk-dotnet");
            body.Add("Policy", policy);

            StsClient client = new StsClient(cred, region, clientProfile);
            GetFederationTokenRequest req = new GetFederationTokenRequest();

            string strParams = JsonConvert.SerializeObject(body);

            req = GetFederationTokenRequest.FromJsonString <GetFederationTokenRequest>(strParams);
            GetFederationTokenResponse resp = client.GetFederationTokenSync(req);
            string jsonString = JsonConvert.SerializeObject(resp);
            Dictionary <string, object> dic = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonString);

            if (dic.ContainsKey("ExpiredTime"))
            {
                dic.Add("StartTime", Int32.Parse(dic["ExpiredTime"].ToString()) - durationSeconds);
            }
            return(dic);
        }
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            Collection<XmlElement> reqParams = new Collection<XmlElement>();
            foreach (XmlElement param in tokenRequirement.AdditionalRequestParameters)
            {
                if (param.NamespaceURI == "urn:oasis:names:tc:SAML:1.0:assertion")
                {
                    reqParams.Add(param);
                }
            }

            ISessionCache cache = (ISessionCache) Activator.CreateInstance(clientCredentials.Cache, clientCredentials.Config);

            //Check the cache for existing session.
            String id;
            List<String> idSort;
            id = clientCredentials.ClientCertificate.Certificate.Thumbprint + ";";
            id += clientCredentials.Session.Thumbprint + ";";
            idSort = new List<string>();
            foreach (XmlElement reqParam in reqParams)
            {
                String val;
                val = "{" + reqParam.GetAttribute("AttributeNamespace") + "}";
                val += reqParam.GetAttribute("AttributeName");
                val += "=";
                val += reqParam.GetElementsByTagName("AttributeValue", "urn:oasis:names:tc:SAML:1.0:assertion")[0].InnerText;
                val += ";";
                idSort.Add(val);
            }
            idSort.Sort();
            foreach (String val in idSort)
            {
                id += val;
            }
            idSort = new List<string>();
            foreach (ClaimTypeRequirement req in tokenRequirement.ClaimTypeRequirements)
            {
                String val = req.ClaimType + ";";
                idSort.Add(val);
            }
            idSort.Sort();
            foreach (String val in idSort)
            {
                id += val;
            }

            XmlNamespaceManager nsmngr = null;
            DateTime notOnOrAfter = DateTime.MinValue;

            //Get the value from the cache
            XmlElement assertion = cache.Get(id);

            //If cache had a result, check if it is still valid
            if (assertion != null)
            {
                nsmngr = new XmlNamespaceManager(assertion.OwnerDocument.NameTable);
                nsmngr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

                notOnOrAfter = DateTime.Parse(assertion.SelectSingleNode("saml:Conditions/@NotOnOrAfter", nsmngr).Value, null, DateTimeStyles.RoundtripKind);

                if (notOnOrAfter < DateTime.UtcNow)
                {
                    assertion = null;
                    cache.Remove(id);
                }
            }

            //If the cache wasn't successful, create new.
            if (assertion == null)
            {
                //Get a new assertion token for the session
                StsClient target = new StsClient(tokenRequirement.IssuerBinding, tokenRequirement.IssuerAddress);
                target.Endpoint.Behaviors.Remove<ClientCredentials>();
                target.Endpoint.Behaviors.Add(new OptClientCredentials());
                target.ClientCredentials.ClientCertificate.Certificate = clientCredentials.ClientCertificate.Certificate;
                target.InnerChannel.OperationTimeout = timeout;

                assertion = target.RequestTicket("Anonymous", clientCredentials.Session, clientCredentials.Duration, reqParams, tokenRequirement.ClaimTypeRequirements);

                nsmngr = new XmlNamespaceManager(assertion.OwnerDocument.NameTable);
                nsmngr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

                notOnOrAfter = DateTime.Parse(assertion.SelectSingleNode("saml:Conditions/@NotOnOrAfter", nsmngr).Value, null, DateTimeStyles.RoundtripKind);

                cache.Add(id, assertion, notOnOrAfter);
            }

            //Get some date from the assertion token
            DateTime notBefore = DateTime.Parse(assertion.SelectSingleNode("saml:Conditions/@NotBefore", nsmngr).Value, null, DateTimeStyles.RoundtripKind);
            String assertionId = assertion.SelectSingleNode("@AssertionID", nsmngr).Value;

            // Create a KeyIdentifierClause for the SamlSecurityToken
            SamlAssertionKeyIdentifierClause samlKeyIdentifierClause = new SamlAssertionKeyIdentifierClause(assertionId);

            return new GenericXmlSecurityToken(assertion, new X509SecurityToken(clientCredentials.Session), notBefore, notOnOrAfter, samlKeyIdentifierClause, samlKeyIdentifierClause, null);
        }
Example #17
0
        public string Index(string httpMethod, string path, string queries, string headers, string policy, string sts, string callback)
        {
            string ak = "<your ak>";
            string sk = "<your sk>";
            BceClientConfiguration config = new BceClientConfiguration()
            {
                Credentials = new DefaultBceCredentials(ak, sk)
            };

            string result = null;

            if (sts != null)
            {
                StsClient client               = new StsClient(config);
                string    accessControlList    = sts;
                GetSessionTokenRequest request = new GetSessionTokenRequest()
                {
                    DurationSeconds   = 60 * 60 * 24,
                    AccessControlList = accessControlList
                };
                GetSessionTokenResponse response = client.GetSessionToken(request);
                result = JsonConvert.SerializeObject(response);
            }
            else if (policy != null)
            {
                string base64    = Convert.ToBase64String(Encoding.UTF8.GetBytes(policy));
                var    hash      = new HMACSHA256(Encoding.UTF8.GetBytes(sk));
                string signature = EncodeHex(hash.ComputeHash(Encoding.UTF8.GetBytes(base64)));
                result = JsonConvert.SerializeObject(new PolicySignatureResult()
                {
                    policy    = base64,
                    signature = signature,
                    accessKey = ak,
                });
            }
            else
            {
                InternalRequest internalRequest = new InternalRequest();
                internalRequest.Config     = config;
                internalRequest.Uri        = new Uri("http://www.baidu.com" + path);
                internalRequest.HttpMethod = httpMethod;
                if (headers != null)
                {
                    internalRequest.Headers = JsonConvert.DeserializeObject <Dictionary <string, string> > (headers);
                }
                if (queries != null)
                {
                    internalRequest.Parameters = JsonConvert.DeserializeObject <Dictionary <string, string> > (queries);
                }

                BceV1Signer bceV1Signer = new BceV1Signer();
                string      sign        = bceV1Signer.Sign(internalRequest);

                string xbceDate = DateUtils.FormatAlternateIso8601Date(DateTime.Now);
                result = JsonConvert.SerializeObject(new SignatureResult()
                {
                    statusCode = 200,
                    signature  = sign,
                    xbceDate   = xbceDate,
                });
            }

            if (callback != null)
            {
                result = callback + "(" + result + ")";
            }

            return(result);
        }
Example #18
0
        public void AllNull()
        {
            StsClient target = new StsClient(new StsBinding(), new EndpointAddress("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"));

            target.RequestTicket(null, null, DateTime.MinValue, DateTime.MaxValue, null, null);
        }