示例#1
0
        private async static Task RunSample()
        {
            // All settings are stored in web.config
            string authenticationUrl   = ConfigurationManager.AppSettings["AuthenticationUrl"] + "/AuthnRequest";
            string appUrl              = ConfigurationManager.AppSettings["AppUrl"];
            string partnerIdpUrl       = ConfigurationManager.AppSettings["PartnerIdpUrl"];
            string userId              = ConfigurationManager.AppSettings["UserId"];
            string appKey              = ConfigurationManager.AppSettings["AppKey"];
            string appSecret           = ConfigurationManager.AppSettings["AppSecret"];
            string clientCertNumber    = ConfigurationManager.AppSettings["ClientCertificateSerialNumber"];
            string saxoCertNumber      = ConfigurationManager.AppSettings["SaxoBankCertificateSerialNumber"];
            string clientsMeRequestUrl = ConfigurationManager.AppSettings["OpenApiBaseUrl"] + "/port/v1/clients/me";

            // Get the certificates (assumed installed on the local cert store, serial numbers are set up in the config-file)
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

            X509Certificate2 clientCertificate     = store.Certificates.Find(X509FindType.FindBySerialNumber, clientCertNumber, false)[0];
            X509Certificate2 encryptionCertificate = store.Certificates.Find(X509FindType.FindBySerialNumber, saxoCertNumber, false)[0];

            // Parse the saml to get the authorizationCode and fetch the token
            OpenApiOAuth2TokenResponse tokenResponse = OpenApiAuthHelper.GetTokenByClientCertificate(clientCertificate, encryptionCertificate, appUrl, partnerIdpUrl, userId, appKey, appSecret, authenticationUrl).Result;

            // Use the access token to retrieve OpenApi data from the port/clients/me endpoint
            var openApiTestData = await GetClientsMe(tokenResponse, clientsMeRequestUrl).ConfigureAwait(false);

            Console.WriteLine("The OpenApi Endpoint \"/port/v1/clients/me\" returned the following data:\n\n" + openApiTestData);
        }
        public static async Task <OpenApiOAuth2TokenResponse> GetTokenByClientCertificate(
            X509Certificate2 clientCert,
            X509Certificate2 encryptionCert,
            string appUrl,
            string partnerIdpUrl,
            string userId,
            string appKey,
            string appSecret,
            string authenticationUrl)
        {
            string samlRequest = CreateAuthnRequest(appUrl, partnerIdpUrl, userId, appKey, appSecret, clientCert, encryptionCert);

            string responseString = await SendSamlRequest(samlRequest, authenticationUrl);

            XmlElement soapResponseXml = GetXmlElement(responseString);

            if (soapResponseXml == null)
            {
                return(null);
            }

            XmlNamespaceManager xmlns = new XmlNamespaceManager(soapResponseXml.OwnerDocument.NameTable);

            xmlns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            XmlNode oaTokenNode =
                soapResponseXml.SelectSingleNode("//saml:Attribute[@Name='OpenApiToken']/saml:AttributeValue", xmlns);

            if (oaTokenNode == null)
            {
                return(null);
            }

            return(OpenApiOAuth2TokenResponse.ParseToken(oaTokenNode.InnerText));
        }
        public static OpenApiOAuth2TokenResponse ParseToken(string tokenXml)
        {
            Stream tokenStream = new MemoryStream(Encoding.UTF8.GetBytes(tokenXml));
            DataContractJsonSerializer serializer    = new DataContractJsonSerializer(typeof(OpenApiOAuth2TokenResponse));
            OpenApiOAuth2TokenResponse tokenResponse = serializer.ReadObject(tokenStream) as OpenApiOAuth2TokenResponse;

            if (tokenResponse == null)
            {
                throw new Exception("Unable to read token response");
            }
            return(tokenResponse);
        }
        private static void InitializeHttpClient(OpenApiOAuth2TokenResponse token)
        {
            // Initialize httpClient with cookie container to ensure stickiness and automatic decompression of recieved data.
            // Note that in production code this must be disposed correctly.
            _cookieContainer = new CookieContainer();
            var clientHandler = new HttpClientHandler
            {
                CookieContainer        = _cookieContainer,
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
                UseDefaultCredentials  = true
            };

            _httpClient = new HttpClient(clientHandler);
            // Set the Token (and type) directly in the Authorization Header for the request
            _httpClient.DefaultRequestHeaders.Add("Authorization", $"{token.TokenType} {token.AccessToken}");
        }
示例#5
0
        private async static Task <string> GetClientsMe(OpenApiOAuth2TokenResponse token, string clientsMeRequestUrl)
        {
            // Initialize httpClient with cookie container to ensure stickiness and automatic decompression of recieved data. Note that in production code
            // this must be disposed correctly
            HttpClient httpClient = new HttpClient(
                new HttpClientHandler
            {
                CookieContainer        = new CookieContainer(),
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
                UseDefaultCredentials  = true
            });

            // Set the Token (and type) directly in the Authorization Header for the request
            httpClient.DefaultRequestHeaders.Add("Authorization", $"{token.TokenType} {token.AccessToken}");

            HttpResponseMessage response = await httpClient.GetAsync(new Uri(clientsMeRequestUrl)).ConfigureAwait(false);

            return(await response.Content.ReadAsStringAsync());
        }
        private async static Task <string> GetClientsMe(OpenApiOAuth2TokenResponse token, string clientsMeRequestUrl)
        {
            HttpResponseMessage response = await _httpClient.GetAsync(new Uri(clientsMeRequestUrl)).ConfigureAwait(false);

            return(await response.Content.ReadAsStringAsync());
        }