コード例 #1
0
        private static async Task <AuthenticationParameters> CreateFromResourceUrlCommonAsync(Uri resourceUrl)
        {
            if (resourceUrl == null)
            {
                throw new ArgumentNullException("resourceUrl");
            }

            AuthenticationParameters authParams;

            try
            {
                IHttpClient request = PlatformPlugin.HttpClientFactory.Create(resourceUrl.AbsoluteUri, null);
                using (await request.GetResponseAsync())
                {
                    var ex = new AdalException(AdalError.UnauthorizedResponseExpected);
                    PlatformPlugin.Logger.Error(null, ex);
                    throw ex;
                }
            }
            catch (HttpRequestWrapperException ex)
            {
                IHttpWebResponse response = ex.WebResponse;
                if (response == null)
                {
                    var serviceEx = new AdalServiceException(AdalErrorMessage.UnauthorizedHttpStatusCodeExpected, ex);
                    PlatformPlugin.Logger.Error(null, serviceEx);
                    throw serviceEx;
                }

                authParams = CreateFromUnauthorizedResponseCommon(response);
            }

            return(authParams);
        }
コード例 #2
0
        internal static async Task <XDocument> FetchMexAsync(string federationMetadataUrl, CallState callState)
        {
            XDocument mexDocument;

            try
            {
                IHttpWebRequest request = PlatformPlugin.HttpWebRequestFactory.Create(federationMetadataUrl);
                request.Method = "GET";
                using (var response = await request.GetResponseSyncOrAsync(callState))
                {
                    mexDocument = XDocument.Load(response.GetResponseStream(), LoadOptions.None);
                }
            }
            catch (WebException ex)
            {
                var serviceEx = new AdalServiceException(AdalError.AccessingWsMetadataExchangeFailed, ex);
                PlatformPlugin.Logger.LogException(callState, serviceEx);
                throw serviceEx;
            }
            catch (XmlException ex)
            {
                var adalEx = new AdalException(AdalError.ParsingWsMetadataExchangeFailed, ex);
                PlatformPlugin.Logger.LogException(callState, adalEx);
                throw adalEx;
            }

            return(mexDocument);
        }
コード例 #3
0
        internal void LogException(CallState callState, Exception ex)
        {
            ArgumentException argumentEx = ex as ArgumentException;

            if (argumentEx != null)
            {
                Information(callState, "ArgumentException was thrown for argument '{0}' with message '{1}'", argumentEx.ParamName, argumentEx.Message);
                return;
            }

            AdalServiceException adalServiceEx = ex as AdalServiceException;

            if (adalServiceEx != null)
            {
                Information(callState, "AdalServiceException was thrown with ErrorCode '{0}' and StatusCode '{1}' and innerException '{2}'",
                            adalServiceEx.ErrorCode, adalServiceEx.StatusCode, (adalServiceEx.InnerException != null) ? adalServiceEx.Message : "No inner exception");
                return;
            }

            AdalException adalEx = ex as AdalException;

            if (adalEx != null)
            {
                Information(callState, "AdalException was thrown with ErrorCode '{0}'", adalEx.ErrorCode);
                return;
            }

            Information(callState, "Exception of type '{0}' was thrown with message '{1}'", ex.GetType().ToString(), ex.Message);
        }
コード例 #4
0
 private void SetRedirectUriRequestParameter()
 {
     if (ReferenceEquals(this.redirectUri, Constant.SsoPlaceHolderUri))
     {
         try
         {
             this.redirectUriRequestParameter = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri;
         }
         catch (FormatException ex)
         {
             // This is the workaround for a bug in managed Uri class of WinPhone SDK which makes it throw UriFormatException when it gets called from unmanaged code.
             const string CurrentApplicationCallbackUriSetting = "CurrentApplicationCallbackUri";
             if (ApplicationData.Current.LocalSettings.Values.ContainsKey(CurrentApplicationCallbackUriSetting))
             {
                 this.redirectUriRequestParameter = (string)ApplicationData.Current.LocalSettings.Values[CurrentApplicationCallbackUriSetting];
             }
             else
             {
                 var adalEx = new AdalException(AdalError.NeedToSetCallbackUriAsLocalSetting, AdalErrorMessage.NeedToSetCallbackUriAsLocalSetting, ex);
                 Logger.LogException(this.CallState, adalEx);
                 throw adalEx;
             }
         }
     }
     else
     {
         this.redirectUriRequestParameter = redirectUri.AbsoluteUri;
     }
 }
        public async Task VerifyAnotherHostByInstanceDiscoveryAsync(string host, string tenant, CallState callState)
        {
            string instanceDiscoveryEndpoint = this.InstanceDiscoveryEndpoint;

            instanceDiscoveryEndpoint += ("?api-version=1.0&authorization_endpoint=" + AuthorizeEndpointTemplate);
            instanceDiscoveryEndpoint  = instanceDiscoveryEndpoint.Replace("{host}", host);
            instanceDiscoveryEndpoint  = instanceDiscoveryEndpoint.Replace("{tenant}", tenant);

            instanceDiscoveryEndpoint = HttpHelper.CheckForExtraQueryParameter(instanceDiscoveryEndpoint);

            ClientMetrics clientMetrics = new ClientMetrics();

            try
            {
                IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(instanceDiscoveryEndpoint);
                request.Method = "GET";
                HttpHelper.AddCorrelationIdHeadersToRequest(request, callState);
                AdalIdHelper.AddAsHeaders(request);

                clientMetrics.BeginClientMetricsRecord(request, callState);

                using (var response = await request.GetResponseSyncOrAsync(callState))
                {
                    HttpHelper.VerifyCorrelationIdHeaderInReponse(response, callState);
                    InstanceDiscoveryResponse discoveryResponse = HttpHelper.DeserializeResponse <InstanceDiscoveryResponse>(response);
                    clientMetrics.SetLastError(null);
                    if (discoveryResponse.TenantDiscoveryEndpoint == null)
                    {
                        var ex = new AdalException(AdalError.AuthorityNotInValidList);
                        Logger.LogException(null, ex);
                        throw ex;
                    }
                }
            }
            catch (WebException ex)
            {
                TokenResponse tokenResponse = OAuth2Response.ReadErrorResponse(ex.Response);
                clientMetrics.SetLastError(tokenResponse.ErrorCodes);

                if (tokenResponse.Error == "invalid_instance")
                {
                    var serviceEx = new AdalServiceException(AdalError.AuthorityNotInValidList, ex);
                    Logger.LogException(null, serviceEx);
                    throw serviceEx;
                }
                else
                {
                    var serviceEx = new AdalServiceException(
                        AdalError.AuthorityValidationFailed,
                        string.Format(CultureInfo.InvariantCulture, "{0}. {1}: {2}", AdalErrorMessage.AuthorityValidationFailed, tokenResponse.Error, tokenResponse.ErrorDescription),
                        ex);
                    Logger.LogException(null, serviceEx);
                    throw serviceEx;
                }
            }
            finally
            {
                clientMetrics.EndClientMetricsRecord(ClientMetricsEndpointType.InstanceDiscovery, callState);
            }
        }
        protected override async Task PreRunAsync()
        {
            await base.PreRunAsync();

            // We cannot move the following lines to UserCredential as one of these calls in async.
            // It cannot be moved to constructor or property or a pure sync or async call. This is why we moved it here which is an async call already.
            if (string.IsNullOrWhiteSpace(this.userCredential.UserName))
            {
#if ADAL_NET
                this.userCredential.UserName = PlatformSpecificHelper.GetUserPrincipalName();
#else
                this.userCredential.UserName = await PlatformSpecificHelper.GetUserPrincipalNameAsync();
#endif
                if (string.IsNullOrWhiteSpace(userCredential.UserName))
                {
                    Logger.Information(this.CallState, "Could not find UPN for logged in user");
                    var ex = new AdalException(AdalError.UnknownUser);
                    Logger.LogException(this.CallState, ex);
                    throw ex;
                }

                Logger.Information(this.CallState, "Logged in user '{0}' detected", userCredential.UserName);
            }

            this.DisplayableId = userCredential.UserName;
        }
コード例 #7
0
        private static void ThrowAssemlyLoadFailedException(string webAuthenticationDialogAssemblyName, Exception innerException)
        {
            var ex = new AdalException(AdalError.AssemblyLoadFailed,
                                       string.Format(CultureInfo.InvariantCulture, AdalErrorMessage.AssemblyLoadFailedTemplate, webAuthenticationDialogAssemblyName), innerException);

            Logger.LogException(null, ex);
            throw ex;
        }
コード例 #8
0
        private RequestParameters CreateAuthorizationRequest(string loginHint, bool includeFormsAuthParam)
        {
            RequestParameters authorizationRequestParameters = new RequestParameters(this.Resource, this.ClientKey);

            authorizationRequestParameters[OAuthParameter.ResponseType] = OAuthResponseType.Code;

            authorizationRequestParameters[OAuthParameter.RedirectUri] = this.redirectUriRequestParameter;

            if (!string.IsNullOrWhiteSpace(loginHint))
            {
                authorizationRequestParameters[OAuthParameter.LoginHint] = loginHint;
            }

            if (this.CallState != null && this.CallState.CorrelationId != Guid.Empty)
            {
                authorizationRequestParameters[OAuthParameter.CorrelationId] = this.CallState.CorrelationId.ToString();
            }

            // ADFS currently ignores the parameter for now.
            if (promptBehavior == PromptBehavior.Always)
            {
                authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.Login;
            }
            else if (promptBehavior == PromptBehavior.RefreshSession)
            {
                authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.RefreshSession;
            }
            else if (promptBehavior == PromptBehavior.Never)
            {
                authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.AttemptNone;
            }

            if (includeFormsAuthParam)
            {
                authorizationRequestParameters[OAuthParameter.FormsAuth] = OAuthValue.FormsAuth;
            }

            AdalIdHelper.AddAsQueryParameters(authorizationRequestParameters);

            if (!string.IsNullOrWhiteSpace(extraQueryParameters))
            {
                // Checks for extraQueryParameters duplicating standard parameters
                Dictionary <string, string> kvps = EncodingHelper.ParseKeyValueList(extraQueryParameters, '&', false, this.CallState);
                foreach (KeyValuePair <string, string> kvp in kvps)
                {
                    if (authorizationRequestParameters.ContainsKey(kvp.Key))
                    {
                        var ex = new AdalException(AdalError.DuplicateQueryParameter, string.Format(AdalErrorMessage.DuplicateQueryParameterTemplate, kvp.Key));
                        Logger.LogException(this.CallState, ex);
                        throw ex;
                    }
                }

                authorizationRequestParameters.ExtraQueryParameter = extraQueryParameters;
            }

            return(authorizationRequestParameters);
        }
コード例 #9
0
        internal static WsTrustResponse CreateFromResponseDocument(XDocument responseDocument)
        {
            Dictionary <string, string> tokenResponseDictionary = new Dictionary <string, string>();

            try
            {
                XElement requestSecurityTokenResponseCollection =
                    responseDocument.Descendants(XmlNamespace.Trust + "RequestSecurityTokenResponseCollection").FirstOrDefault();

                if (requestSecurityTokenResponseCollection != null)
                {
                    IEnumerable <XElement> tokenResponses = responseDocument.Descendants(XmlNamespace.Trust + "RequestSecurityTokenResponse");
                    foreach (var tokenResponse in tokenResponses)
                    {
                        XElement tokenTypeElement = tokenResponse.Elements(XmlNamespace.Trust + "TokenType").FirstOrDefault();
                        if (tokenTypeElement == null)
                        {
                            continue;
                        }

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

                        // TODO #123622: We need to disable formatting due to a potential service bug. Remove the ToString argument when problem is fixed.
                        tokenResponseDictionary.Add(tokenTypeElement.Value, requestedSecurityToken.FirstNode.ToString(SaveOptions.DisableFormatting));
                    }
                }
            }
            catch (XmlException ex)
            {
                var adalEx = new AdalException(AdalError.ParsingWsTrustResponseFailed, ex);
                PlatformPlugin.Logger.LogException(null, adalEx);
                throw adalEx;
            }

            if (tokenResponseDictionary.Count == 0)
            {
                var ex = new AdalException(AdalError.ParsingWsTrustResponseFailed);
                PlatformPlugin.Logger.LogException(null, ex);
                throw ex;
            }

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

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

            return(wsTrustResponse);
        }
コード例 #10
0
 private void ValidateAuthorityType()
 {
     if (!this.SupportADFS && this.Authenticator.AuthorityType == AuthorityType.ADFS)
     {
         PlatformPlugin.Logger.Error(this.CallState, "Invalid authority type '{0}'", this.Authenticator.AuthorityType);
         var ex = new AdalException(AdalError.InvalidAuthorityType,
                                    string.Format(CultureInfo.InvariantCulture, AdalErrorMessage.InvalidAuthorityTypeTemplate, this.Authenticator.Authority));
         PlatformPlugin.Logger.LogException(this.CallState, ex);
         throw ex;
     }
 }
コード例 #11
0
        public async Task <AuthorizationResult> AuthenticateAsync(Uri authorizationUri, Uri redirectUri, CallState callState)
        {
            bool ssoMode = ReferenceEquals(redirectUri, Constant.SsoPlaceHolderUri);

            if (this.promptBehavior == PromptBehavior.Never && !ssoMode && redirectUri.Scheme != Constant.MsAppScheme)
            {
                var ex = new ArgumentException(AdalErrorMessage.RedirectUriUnsupportedWithPromptBehaviorNever, "redirectUri");
                Logger.LogException(callState, ex);
                throw ex;
            }

            WebAuthenticationResult webAuthenticationResult;

            WebAuthenticationOptions options = (this.useCorporateNetwork && (ssoMode || redirectUri.Scheme == Constant.MsAppScheme)) ? WebAuthenticationOptions.UseCorporateNetwork : WebAuthenticationOptions.None;

            if (this.promptBehavior == PromptBehavior.Never)
            {
                options |= WebAuthenticationOptions.SilentMode;
            }

            try
            {
                if (ssoMode)
                {
                    webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri);
                }
                else
                {
                    webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri, redirectUri);
                }
            }
            catch (FileNotFoundException ex)
            {
                var adalEx = new AdalException(AdalError.AuthenticationUiFailed, ex);
                Logger.LogException(callState, adalEx);
                throw adalEx;
            }
            catch (Exception ex)
            {
                if (this.promptBehavior == PromptBehavior.Never)
                {
                    var adalEx = new AdalException(AdalError.UserInteractionRequired, ex);
                    Logger.LogException(callState, adalEx);
                    throw adalEx;
                }

                var uiFailedEx = new AdalException(AdalError.AuthenticationUiFailed, ex);
                Logger.LogException(callState, uiFailedEx);
                throw uiFailedEx;
            }

            return(ProcessAuthorizationResult(webAuthenticationResult, callState));
        }
コード例 #12
0
ファイル: WebUI.cs プロジェクト: mamurshe/PowerBI.Api.Client
 public void Authenticate(Uri authorizationUri, Uri redirectUri, CallState callState)
 {
     try
     {
         this.parameters.CallerViewController.PresentViewController(new AuthenticationAgentUINavigationController(authorizationUri.AbsoluteUri, redirectUri.AbsoluteUri, CallbackMethod), false, null);
     }
     catch (Exception ex)
     {
         var adalEx = new AdalException(AdalError.AuthenticationUiFailed, ex);
         PlatformPlugin.Logger.LogException(callState, ex);
         throw adalEx;
     }
 }
 public static void Log(AdalException authException, ref string strErrors)
 {
     string strMessage = authException.Message;
     string strDetail = null;
     if (authException.InnerException != null)
     {
         // You should implement retry and back-off logic per the guidance given here:http://msdn.microsoft.com/en-us/library/dn168916.aspx
         // InnerException.Message contains the HTTP error status codes mentioned in the link above
         strDetail = authException.InnerException.Message;
         strErrors += strDetail;
     }
     GraphHelperEventSource.Log.AuthFailure(strMessage, strDetail);
 }
コード例 #14
0
 internal static XDocument ReadDocumentFromResponse(Stream responseStream)
 {
     try
     {
         return(XDocument.Load(responseStream, LoadOptions.None));
     }
     catch (XmlException ex)
     {
         var adalEx = new AdalException(AdalError.ParsingWsTrustResponseFailed, ex);
         PlatformPlugin.Logger.LogException(null, adalEx);
         throw adalEx;
     }
 }
コード例 #15
0
        private void VerifyNotOnMainThread()
        {
            Looper looper = Looper.MyLooper();

            if (looper != null && looper == mContext.MainLooper)
            {
                Exception exception = new AdalException(
                    "calling this from your main thread can lead to deadlock");
                CallState.Logger.Error(null, exception);
                if (mContext.ApplicationInfo.TargetSdkVersion >= BuildVersionCodes.Froyo)
                {
                    throw exception;
                }
            }
        }
コード例 #16
0
        public ClientAssertion Sign(ClientAssertionCertificate credential)
        {
            // Base64Url encoded header and claims
            string token = this.Encode(credential);

            // Length check before sign
            if (MaxTokenLength < token.Length)
            {
                var ex = new AdalException(AdalError.EncodedTokenTooLong);
                Logger.LogException(null, ex);
                throw ex;
            }

            return(new ClientAssertion(this.payload.Issuer, string.Concat(token, ".", UrlEncodeSegment(credential.Sign(token)))));
        }
コード例 #17
0
ファイル: WebUI.cs プロジェクト: mamurshe/PowerBI.Api.Client
 public void Authenticate(Uri authorizationUri, Uri redirectUri, CallState callState)
 {
     try
     {
         var agentIntent = new Intent(this.parameters.CallerActivity, typeof(AuthenticationAgentActivity));
         agentIntent.PutExtra("Url", authorizationUri.AbsoluteUri);
         agentIntent.PutExtra("Callback", redirectUri.AbsoluteUri);
         this.parameters.CallerActivity.StartActivityForResult(agentIntent, 0);
     }
     catch (Exception ex)
     {
         var adalEx = new AdalException(AdalError.AuthenticationUiFailed, ex);
         PlatformPlugin.Logger.LogException(callState, ex);
         throw adalEx;
     }
 }
コード例 #18
0
        private void VerifyAuthorizationResult()
        {
            if (this.promptBehavior == PromptBehavior.Never && this.authorizationResult.Error == OAuthError.LoginRequired)
            {
                var ex = new AdalException(AdalError.UserInteractionRequired);
                Logger.LogException(this.CallState, ex);
                throw ex;
            }

            if (this.authorizationResult.Status != AuthorizationStatus.Success)
            {
                var ex = new AdalServiceException(this.authorizationResult.Error, this.authorizationResult.ErrorDescription);
                Logger.LogException(this.CallState, ex);
                throw ex;
            }
        }
        protected override async Task PreTokenRequest()
        {
            await base.PreTokenRequest();

            UserRealmDiscoveryResponse userRealmResponse = await UserRealmDiscoveryResponse.CreateByDiscoveryAsync(this.Authenticator.UserRealmUri, this.userCredential.UserName, this.CallState);

            Logger.Information(this.CallState, "User '{0}' detected as '{1}'", this.userCredential.UserName, userRealmResponse.AccountType);

            if (string.Compare(userRealmResponse.AccountType, "federated", StringComparison.OrdinalIgnoreCase) == 0)
            {
                if (string.IsNullOrWhiteSpace(userRealmResponse.FederationMetadataUrl))
                {
                    var ex = new AdalException(AdalError.MissingFederationMetadataUrl);
                    Logger.LogException(this.CallState, ex);
                    throw ex;
                }

                Uri wsTrustUrl = await MexParser.FetchWsTrustAddressFromMexAsync(userRealmResponse.FederationMetadataUrl, this.userCredential.UserAuthType, this.CallState);

                Logger.Information(this.CallState, "WS-Trust endpoint '{0}' fetched from MEX at '{1}'", wsTrustUrl, userRealmResponse.FederationMetadataUrl);

                WsTrustResponse wsTrustResponse = await WsTrustRequest.SendRequestAsync(wsTrustUrl, this.userCredential, this.CallState);

                Logger.Information(this.CallState, "Token of type '{0}' acquired from WS-Trust endpoint", wsTrustResponse.TokenType);

                // We assume that if the response token type is not SAML 1.1, it is SAML 2
                this.samlAssertion = new UserAssertion(wsTrustResponse.Token, (wsTrustResponse.TokenType == WsTrustResponse.Saml1Assertion) ? OAuthGrantType.Saml11Bearer : OAuthGrantType.Saml20Bearer);
            }
            else if (string.Compare(userRealmResponse.AccountType, "managed", StringComparison.OrdinalIgnoreCase) == 0)
            {
                // handle password grant flow for the managed user
                if (this.userCredential.PasswordToCharArray() == null)
                {
                    var ex = new AdalException(AdalError.PasswordRequiredForManagedUserError);
                    Logger.LogException(this.CallState, ex);
                    throw ex;
                }
            }
            else
            {
                var ex = new AdalException(AdalError.UnknownUserType);
                Logger.LogException(this.CallState, ex);
                throw ex;
            }
        }
コード例 #20
0
        private static async Task <AuthenticationParameters> CreateFromResourceUrlCommonAsync(Uri resourceUrl)
        {
            CallState callState = new CallState(Guid.NewGuid(), false);

            if (resourceUrl == null)
            {
                throw new ArgumentNullException("resourceUrl");
            }

            IHttpWebResponse         response = null;
            AuthenticationParameters authParams;

            try
            {
                IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(resourceUrl.AbsoluteUri);
                request.ContentType = "application/x-www-form-urlencoded";
                response            = await request.GetResponseSyncOrAsync(callState);

                var ex = new AdalException(AdalError.UnauthorizedResponseExpected);
                Logger.Error(null, ex);
                throw ex;
            }
            catch (WebException ex)
            {
                response = NetworkPlugin.HttpWebRequestFactory.CreateResponse(ex.Response);
                if (response == null)
                {
                    var serviceEx = new AdalServiceException(AdalErrorMessage.UnauthorizedHttpStatusCodeExpected, ex);
                    Logger.Error(null, serviceEx);
                    throw serviceEx;
                }

                authParams = CreateFromUnauthorizedResponseCommon(response);
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            return(authParams);
        }
        public async static Task <string> GetUserPrincipalNameAsync()
        {
            if (!Windows.System.UserProfile.UserInformation.NameAccessAllowed)
            {
                var ex = new AdalException(AdalError.CannotAccessUserInformation);
                Logger.LogException(null, ex);
                throw ex;
            }

            try
            {
                return(await Windows.System.UserProfile.UserInformation.GetPrincipalNameAsync());
            }
            catch (UnauthorizedAccessException ex)
            {
                var adalEx = new AdalException(AdalError.UnauthorizedUserInformationAccess, ex);
                Logger.LogException(null, adalEx);
                throw adalEx;
            }
        }
コード例 #22
0
        public void Authenticate(Uri authorizationUri, Uri redirectUri, IDictionary <string, object> headersMap, CallState callState)
        {
            ValueSet set = new ValueSet();

            foreach (string key in headersMap.Keys)
            {
                set[key] = headersMap[key];
            }

            try
            {
                WebAuthenticationBroker.AuthenticateAndContinue(authorizationUri, ReferenceEquals(redirectUri, Constant.SsoPlaceHolderUri) ? null : redirectUri, set, WebAuthenticationOptions.None);
            }
            catch (Exception ex)
            {
                var adalEx = new AdalException(AdalError.AuthenticationUiFailed, ex);
                Logger.LogException(callState, adalEx);
                throw adalEx;
            }
        }
コード例 #23
0
        public static string ReadErrorResponse(XDocument responseDocument, CallState callState)
        {
            string errorMessage = null;

            try
            {
                XElement body = responseDocument.Descendants(XmlNamespace.SoapEnvelope + "Body").FirstOrDefault();

                if (body != null)
                {
                    XElement fault = body.Elements(XmlNamespace.SoapEnvelope + "Fault").FirstOrDefault();
                    if (fault != null)
                    {
                        XElement reason = fault.Elements(XmlNamespace.SoapEnvelope + "Reason").FirstOrDefault();
                        if (reason != null)
                        {
                            XElement text = reason.Elements(XmlNamespace.SoapEnvelope + "Text").FirstOrDefault();
                            if (text != null)
                            {
                                using (var reader = text.CreateReader())
                                {
                                    reader.MoveToContent();
                                    errorMessage = reader.ReadInnerXml();
                                }
                            }
                        }
                    }
                }
            }
            catch (XmlException ex)
            {
                var adalEx = new AdalException(AdalError.ParsingWsTrustResponseFailed, ex);
                PlatformPlugin.Logger.LogException(callState, adalEx);
                throw adalEx;
            }

            return(errorMessage);
        }
コード例 #24
0
        private KeyValuePair <TokenCacheKey, AuthenticationResult>?LoadSingleItemFromCache(string authority, string resource, string clientId, TokenSubjectType subjectType, string uniqueId, string displayableId, CallState callState)
        {
            // First identify all potential tokens.
            List <KeyValuePair <TokenCacheKey, AuthenticationResult> > items = this.QueryCache(authority, clientId, subjectType, uniqueId, displayableId);

            List <KeyValuePair <TokenCacheKey, AuthenticationResult> > resourceSpecificItems =
                items.Where(p => p.Key.ResourceEquals(resource)).ToList();

            int resourceValuesCount = resourceSpecificItems.Count();
            KeyValuePair <TokenCacheKey, AuthenticationResult>?returnValue = null;

            if (resourceValuesCount == 1)
            {
                returnValue = resourceSpecificItems.First();
            }
            else if (resourceValuesCount == 0)
            {
                // There are no resource specific tokens.  Choose any of the MRRT tokens if there are any.
                List <KeyValuePair <TokenCacheKey, AuthenticationResult> > mrrtItems =
                    items.Where(p => p.Value.IsMultipleResourceRefreshToken).ToList();

                if (mrrtItems.Any())
                {
                    returnValue = mrrtItems.First();
                }
            }
            else
            {
                // There is more than one resource specific token.  It is
                // ambiguous which one to return so throw.
                var ex = new AdalException(AdalError.MultipleTokensMatched);
                Logger.LogException(callState, ex);
                throw ex;
            }

            return(returnValue);
        }
コード例 #25
0
        internal static Uri ExtractWsTrustAddressFromMex(XDocument mexDocument, UserAuthType userAuthType, CallState callState)
        {
            Uri url;

            try
            {
                Dictionary <string, MexPolicy> policies = ReadPolicies(mexDocument);
                Dictionary <string, MexPolicy> bindings = ReadPolicyBindings(mexDocument, policies);
                SetPolicyEndpointAddresses(mexDocument, bindings);
                Random    random = new Random();
                MexPolicy policy = policies.Values.Where(p => p.Url != null && p.AuthType == userAuthType).OrderBy(p => random.Next()).FirstOrDefault();
                if (policy != null)
                {
                    url = policy.Url;
                }
                else if (userAuthType == UserAuthType.IntegratedAuth)
                {
                    var ex = new AdalException(AdalError.IntegratedAuthFailed, new AdalException(AdalError.WsTrustEndpointNotFoundInMetadataDocument));
                    PlatformPlugin.Logger.LogException(callState, ex);
                    throw ex;
                }
                else
                {
                    var ex = new AdalException(AdalError.WsTrustEndpointNotFoundInMetadataDocument);
                    PlatformPlugin.Logger.LogException(callState, ex);
                    throw ex;
                }
            }
            catch (XmlException ex)
            {
                var adalEx = new AdalException(AdalError.ParsingWsMetadataExchangeFailed, ex);
                PlatformPlugin.Logger.LogException(callState, adalEx);
                throw adalEx;
            }

            return(url);
        }
        public static string GetUserPrincipalName()
        {
            const int NameUserPrincipal = 8;
            uint      userNameSize      = 0;

            NativeMethods.GetUserNameEx(NameUserPrincipal, null, ref userNameSize);
            if (userNameSize == 0)
            {
                var ex = new AdalException(AdalError.GetUserNameFailed, new Win32Exception(Marshal.GetLastWin32Error()));
                Logger.LogException(null, ex);
                throw ex;
            }

            StringBuilder sb = new StringBuilder((int)userNameSize);

            if (!NativeMethods.GetUserNameEx(NameUserPrincipal, sb, ref userNameSize))
            {
                var ex = new AdalException(AdalError.GetUserNameFailed, new Win32Exception(Marshal.GetLastWin32Error()));
                Logger.LogException(null, ex);
                throw ex;
            }

            return(sb.ToString());
        }
コード例 #27
0
 /// <summary>
 /// Wrap an exception thrown by the ADAL library.  This prevents client dependencies on a particular version fo ADAL.
 /// </summary>
 /// <param name="message">The exception message</param>
 /// <param name="innerException">The inner AdalException with additional details</param>
 internal AuthenticationException(string message, AdalException innerException) : 
     base(string.Format(CultureInfo.CurrentCulture, message, innerException.Message), innerException)
 {
 }
コード例 #28
0
        private static async Task<AuthenticationParameters> CreateFromResourceUrlCommonAsync(Uri resourceUrl)
        {
            if (resourceUrl == null)
            {
                throw new ArgumentNullException("resourceUrl");
            }

            AuthenticationParameters authParams;

            try
            {
                IHttpClient request = PlatformPlugin.HttpClientFactory.Create(resourceUrl.AbsoluteUri, null);
                using (await request.GetResponseAsync())
                {
                    var ex = new AdalException(AdalError.UnauthorizedResponseExpected);
                    PlatformPlugin.Logger.Error(null, ex);
                    throw ex;                    
                }
            }
            catch (HttpRequestWrapperException ex)
            {
                IHttpWebResponse response = ex.WebResponse;
                if (response == null)
                {
                    var serviceEx = new AdalServiceException(AdalErrorMessage.UnauthorizedHttpStatusCodeExpected, ex);
                    PlatformPlugin.Logger.Error(null, serviceEx);
                    throw serviceEx;
                }

                authParams = CreateFromUnauthorizedResponseCommon(response);
            }

            return authParams;
        }
        public async Task AuthenticateResourceAsync_HandleAdalException()
        {
            this.adalServiceInfo.ClientSecret = "clientSecret";

            var resource = "https://resource.sharepoint.com/";
            var expectedAuthenticationResult = new MockAuthenticationResult();

            var adalException = new AdalException("code");

            this.authenticationContextWrapper
                .Setup(wrapper => wrapper.AcquireTokenByAuthorizationCodeAsync(
                    It.IsAny<string>(),
                    It.IsAny<Uri>(),
                    It.IsAny<ClientCredential>(),
                    It.IsAny<string>()))
                .Throws(adalException);

            try
            {
                var authenticationResult = await this.authenticationProvider.AuthenticateResourceAsyncWrapper(resource);
            }
            catch (OneDriveException exception)
            {
                Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), exception.Error.Code, "Unexpected error thrown.");
                Assert.AreEqual("An error occurred during Azure Active Directory authentication.", exception.Error.Message, "Unexpected error thrown.");
                Assert.AreEqual(adalException, exception.InnerException, "Unexpected inner exception.");
                throw;
            }
        }
        private static async Task<AuthenticationParameters> CreateFromResourceUrlCommonAsync(Uri resourceUrl)
        {
            CallState callState = new CallState(Guid.NewGuid(), false);

            if (resourceUrl == null)
            {
                throw new ArgumentNullException("resourceUrl");
            }

            IHttpWebResponse response = null;
            AuthenticationParameters authParams;

            try
            {
                IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(resourceUrl.AbsoluteUri);
                request.ContentType = "application/x-www-form-urlencoded";
                response = await request.GetResponseSyncOrAsync(callState);
                var ex = new AdalException(AdalError.UnauthorizedResponseExpected);
                Logger.Error(null, ex);
                throw ex;
            }
            catch (WebException ex)
            {
                response = NetworkPlugin.HttpWebRequestFactory.CreateResponse(ex.Response);
                if (response == null)
                {
                    var serviceEx = new AdalServiceException(AdalErrorMessage.UnauthorizedHttpStatusCodeExpected, ex);
                    Logger.Error(null, serviceEx);
                    throw serviceEx;
                }

                authParams = CreateFromUnauthorizedResponseCommon(response);
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }

            return authParams;
        }