示例#1
0
        internal async Task <WsTrustResponse> GetWsTrustResponseAsync(
            UserAuthType userAuthType,
            string cloudAudienceUrn,
            WsTrustEndpoint endpoint,
            string username,
            SecureString securePassword)
        {
            string wsTrustRequestMessage = userAuthType == UserAuthType.IntegratedAuth
                ? endpoint.BuildTokenRequestMessageWindowsIntegratedAuth(cloudAudienceUrn)
                : endpoint.BuildTokenRequestMessageUsernamePassword(
                cloudAudienceUrn,
                username,
                new string(securePassword.PasswordToCharArray()));

            try
            {
                WsTrustResponse wsTrustResponse = await _serviceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(
                    endpoint, wsTrustRequestMessage, _requestContext).ConfigureAwait(false);

                _requestContext.Logger.Info($"Token of type '{wsTrustResponse.TokenType}' acquired from WS-Trust endpoint. ");
                return(wsTrustResponse);
            }
            catch (Exception ex)
            {
                throw new MsalClientException(
                          MsalError.ParsingWsTrustResponseFailed,
                          ex.Message,
                          ex);
            }
        }
        internal async Task <WsTrustResponse> GetWsTrustResponseAsync(
            UserAuthType userAuthType,
            string cloudAudienceUrn,
            WsTrustEndpoint endpoint,
            string username,
            SecureString securePassword)
        {
            string wsTrustRequestMessage = userAuthType == UserAuthType.IntegratedAuth
                ? endpoint.BuildTokenRequestMessageWindowsIntegratedAuth(cloudAudienceUrn)
                : endpoint.BuildTokenRequestMessageUsernamePassword(
                cloudAudienceUrn,
                username,
                new string(securePassword.PasswordToCharArray()));

            try
            {
                WsTrustResponse wsTrustResponse = await _serviceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(
                    endpoint, wsTrustRequestMessage, _requestContext).ConfigureAwait(false);

                _requestContext.Logger.Info($"Token of type '{wsTrustResponse.TokenType}' acquired from WS-Trust endpoint. ");
                return(wsTrustResponse);
            }
            catch (Exception ex)
            {
                throw new MsalClientException(
                          MsalError.ParsingWsTrustResponseFailed,
                          "There was an error parsing WS-Trust response from the endpoint. This may occur if there is an issue with your ADFS configuration."
                          + " See https://aka.ms/msal-net-iwa-troubleshooting for more details. Error Message: " + ex.Message,
                          ex);
            }
        }
        internal async Task <WsTrustResponse> GetWsTrustResponseAsync(
            UserAuthType userAuthType,
            string cloudAudienceUrn,
            WsTrustEndpoint endpoint,
            IUsernameInput usernameInput)
        {
            // TODO: need to clean up the casting to UsernamePasswordInput as well as removing the PasswordToCharArray
            // since we're putting the strings onto the managed heap anyway.
            string wsTrustRequestMessage = userAuthType == UserAuthType.IntegratedAuth
                ? endpoint.BuildTokenRequestMessageWindowsIntegratedAuth(cloudAudienceUrn)
                : endpoint.BuildTokenRequestMessageUsernamePassword(
                cloudAudienceUrn,
                usernameInput.UserName,
                new string(((UsernamePasswordInput)usernameInput).PasswordToCharArray()));

            try
            {
                WsTrustResponse wsTrustResponse = await _serviceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(
                    endpoint, wsTrustRequestMessage, _requestContext).ConfigureAwait(false);

                _requestContext.Logger.Info($"Token of type '{wsTrustResponse.TokenType}' acquired from WS-Trust endpoint");
                return(wsTrustResponse);
            }
            catch (Exception ex)
            {
                throw MsalExceptionFactory.GetClientException(
                          CoreErrorCodes.ParsingWsTrustResponseFailed,
                          ex.Message,
                          ex);
            }
        }
        /// <inheritdoc/>
        public async Task <WsTrustResponse> GetWsTrustResponseAsync(
            WsTrustEndpoint wsTrustEndpoint,
            string wsTrustRequest,
            RequestContext requestContext)
        {
            var headers = new Dictionary <string, string>
            {
                { "SOAPAction", (wsTrustEndpoint.Version == WsTrustVersion.WsTrust2005) ? XmlNamespace.Issue2005.ToString() : XmlNamespace.Issue.ToString() }
            };

            var body = new StringContent(
                wsTrustRequest,
                Encoding.UTF8, "application/soap+xml");

            HttpResponse resp = await _httpManager.SendPostForceResponseAsync(wsTrustEndpoint.Uri,
                                                                              headers,
                                                                              body,
                                                                              requestContext.Logger,
                                                                              cancellationToken : requestContext.UserCancellationToken).ConfigureAwait(false);

            if (resp.StatusCode != System.Net.HttpStatusCode.OK)
            {
                string errorMessage = null;
                try
                {
                    errorMessage = WsTrustResponse.ReadErrorResponse(XDocument.Parse(resp.Body, LoadOptions.None), requestContext);
                }
                catch (System.Xml.XmlException)
                {
                    errorMessage = resp.Body;
                }

                string message = string.Format(
                    CultureInfo.CurrentCulture,
                    MsalErrorMessage.FederatedServiceReturnedErrorTemplate,
                    wsTrustEndpoint.Uri,
                    errorMessage);

                throw MsalServiceExceptionFactory.FromHttpResponse(
                          MsalError.FederatedServiceReturnedError,
                          message,
                          resp);
            }

            try
            {
                return(WsTrustResponse.CreateFromResponse(resp.Body, wsTrustEndpoint.Version));
            }
            catch (System.Xml.XmlException ex)
            {
                string message = string.Format(
                    CultureInfo.CurrentCulture,
                    MsalErrorMessage.ParsingWsTrustResponseFailedErrorTemplate,
                    wsTrustEndpoint.Uri,
                    resp.Body);

                throw new MsalClientException(
                          MsalError.ParsingWsTrustResponseFailed, message, ex);
            }
        }
        /// <inheritdoc/>
        public async Task <WsTrustResponse> GetWsTrustResponseAsync(
            WsTrustEndpoint wsTrustEndpoint,
            string wsTrustRequest,
            RequestContext requestContext)
        {
            var headers = new Dictionary <string, string>
            {
                { "ContentType", "application/soap+xml" },
                { "SOAPAction", (wsTrustEndpoint.Version == WsTrustVersion.WsTrust2005) ? XmlNamespace.Issue2005.ToString() : XmlNamespace.Issue.ToString() }
            };

            var body = new StringContent(
                wsTrustRequest,
                Encoding.UTF8, headers["ContentType"]);

            IHttpWebResponse resp = await _httpManager.SendPostForceResponseAsync(wsTrustEndpoint.Uri, headers, body, requestContext).ConfigureAwait(false);

            if (resp.StatusCode != System.Net.HttpStatusCode.OK)
            {
                string errorMessage = null;
                try
                {
                    errorMessage = WsTrustResponse.ReadErrorResponse(XDocument.Parse(resp.Body, LoadOptions.None), requestContext);
                }
                catch (System.Xml.XmlException)
                {
                    errorMessage = resp.Body;
                }

                throw MsalExceptionFactory.GetServiceException(
                          CoreErrorCodes.FederatedServiceReturnedError,
                          string.Format(
                              CultureInfo.CurrentCulture,
                              CoreErrorMessages.FederatedServiceReturnedErrorTemplate,
                              wsTrustEndpoint.Uri,
                              errorMessage),
                          new ExceptionDetail()
                {
                    StatusCode          = (int)resp.StatusCode,
                    ResponseBody        = resp.Body,
                    HttpResponseHeaders = resp.Headers
                });
            }

            try
            {
                return(WsTrustResponse.CreateFromResponse(resp.Body, wsTrustEndpoint.Version));
            }
            catch (System.Xml.XmlException ex)
            {
                throw MsalExceptionFactory.GetClientException(
                          CoreErrorCodes.ParsingWsTrustResponseFailed, CoreErrorCodes.ParsingWsTrustResponseFailed, ex);
            }
        }
示例#6
0
        public async Task <WsTrustResponse> PerformWsTrustMexExchangeAsync(
            string federationMetadataUrl, string cloudAudienceUrn, UserAuthType userAuthType, string username, SecureString password, string federationMetadataFilename)
        {
            MexDocument mexDocument;

            try
            {
                mexDocument = await _serviceBundle.WsTrustWebRequestManager.GetMexDocumentAsync(
                    federationMetadataUrl,
                    _requestContext,
                    federationMetadataFilename).ConfigureAwait(false);
            }
            catch (XmlException ex)
            {
                throw new MsalClientException(
                          MsalError.ParsingWsMetadataExchangeFailed,
                          MsalErrorMessage.ParsingMetadataDocumentFailed,
                          ex);
            }

            WsTrustEndpoint wsTrustEndpoint = userAuthType == UserAuthType.IntegratedAuth
                ? mexDocument.GetWsTrustWindowsTransportEndpoint()
                : mexDocument.GetWsTrustUsernamePasswordEndpoint();

            if (wsTrustEndpoint == null)
            {
                throw new MsalClientException(
                          MsalError.WsTrustEndpointNotFoundInMetadataDocument,
                          MsalErrorMessage.WsTrustEndpointNotFoundInMetadataDocument);
            }

            _requestContext.Logger.InfoPii(
                string.Format(CultureInfo.InvariantCulture, "WS-Trust endpoint '{0}' being used from MEX at '{1}'", wsTrustEndpoint.Uri, federationMetadataUrl),
                "Fetched and parsed MEX. ");

            WsTrustResponse wsTrustResponse = await GetWsTrustResponseAsync(
                userAuthType,
                cloudAudienceUrn,
                wsTrustEndpoint,
                username,
                password).ConfigureAwait(false);

            _requestContext.Logger.Info($"Token of type '{wsTrustResponse.TokenType}' acquired from WS-Trust endpoint. ");

            return(wsTrustResponse);
        }
示例#7
0
        internal static WsTrustResponse CreateFromResponseDocument(XDocument responseDocument, WsTrustVersion version)
        {
            Dictionary <string, string> tokenResponseDictionary = new Dictionary <string, string>();

            XNamespace t = XmlNamespace.Trust;

            if (version == WsTrustVersion.WsTrust2005)
            {
                t = XmlNamespace.Trust2005;
            }

            bool parseResponse = true;

            if (version == WsTrustVersion.WsTrust13)
            {
                XElement requestSecurityTokenResponseCollection =
                    responseDocument.Descendants(t + "RequestSecurityTokenResponseCollection").FirstOrDefault();

                if (requestSecurityTokenResponseCollection == null)
                {
                    parseResponse = false;
                }
            }

            if (!parseResponse)
            {
                return(null);
            }

            IEnumerable <XElement> tokenResponses =
                responseDocument.Descendants(t + "RequestSecurityTokenResponse");

            foreach (var tokenResponse in tokenResponses)
            {
                XElement tokenTypeElement = tokenResponse.Elements(t + "TokenType").FirstOrDefault();
                if (tokenTypeElement == null)
                {
                    continue;
                }

                XElement requestedSecurityToken =
                    tokenResponse.Elements(t + "RequestedSecurityToken").FirstOrDefault();
                if (requestedSecurityToken == null)
                {
                    continue;
                }

                var token = new System.Text.StringBuilder();
                foreach (var node in requestedSecurityToken.Nodes())
                {
                    // Since we moved from XDocument.Load(..., LoadOptions.None) to Load(..., LoadOptions.PreserveWhitespace),
                    // requestedSecurityToken can contain multiple nodes, and the first node is possibly just whitespaces e.g. "\n   ",
                    // so we concatenate all the sub-nodes to include everything
                    token.Append(node.ToString(SaveOptions.DisableFormatting));
                }

                tokenResponseDictionary.Add(tokenTypeElement.Value, token.ToString());
            }

            if (tokenResponseDictionary.Count == 0)
            {
                return(null);
            }

            string tokenType = tokenResponseDictionary.ContainsKey(Saml1Assertion)
                ? Saml1Assertion
                : tokenResponseDictionary.Keys.First();

            WsTrustResponse wsTrustResponse = new WsTrustResponse
            {
                TokenType = tokenType,
                Token     = tokenResponseDictionary[tokenType]
            };

            return(wsTrustResponse);
        }