예제 #1
0
        public AuthorizationResult ProcessAuthorizationResult(IWebAuthenticationBrokerContinuationEventArgs args, CallState callState)
        {
            AuthorizationResult result;

            switch (args.WebAuthenticationResult.ResponseStatus)
            {
            case WebAuthenticationStatus.Success:
                // Issue #129 - Windows Phone cannot handle ms-app URI's so use the placeholder URI for SSO
                var responseData = args.WebAuthenticationResult.ResponseData;
                if (responseData.StartsWith(Constant.MsAppScheme, StringComparison.OrdinalIgnoreCase))
                {
                    responseData = Constant.SsoPlaceHolderUri + responseData.Substring(responseData.IndexOf('?'));
                }

                result = OAuth2Response.ParseAuthorizeResponse(responseData, callState);
                break;

            case WebAuthenticationStatus.ErrorHttp:
                result = new AuthorizationResult(AdalError.AuthenticationFailed, args.WebAuthenticationResult.ResponseErrorDetail.ToString());
                break;

            case WebAuthenticationStatus.UserCancel:
                result = new AuthorizationResult(AdalError.AuthenticationCanceled, AdalErrorMessage.AuthenticationCanceled);
                break;

            default:
                result = new AuthorizationResult(AdalError.AuthenticationFailed, AdalErrorMessage.AuthorizationServerInvalidResponse);
                break;
            }

            return(result);
        }
        public static async Task <T> SendPostRequestAndDeserializeJsonResponseAsync <T>(string uri, RequestParameters requestParameters, CallState callState)
        {
            ClientMetrics clientMetrics = new ClientMetrics();

            try
            {
                IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(uri);
                request.ContentType = "application/x-www-form-urlencoded";
                AddCorrelationIdHeadersToRequest(request, callState);
                AdalIdHelper.AddAsHeaders(request);

                clientMetrics.BeginClientMetricsRecord(request, callState);

                SetPostRequest(request, requestParameters, callState);
                using (IHttpWebResponse response = await request.GetResponseSyncOrAsync(callState))
                {
                    VerifyCorrelationIdHeaderInReponse(response, callState);
                    clientMetrics.SetLastError(null);
                    return(DeserializeResponse <T>(response));
                }
            }
            catch (WebException ex)
            {
                TokenResponse tokenResponse = OAuth2Response.ReadErrorResponse(ex.Response);
                clientMetrics.SetLastError(tokenResponse != null ? tokenResponse.ErrorCodes : null);
                throw new AdalServiceException(tokenResponse.Error, tokenResponse.ErrorDescription, tokenResponse.ErrorCodes, ex);
            }
            finally
            {
                clientMetrics.EndClientMetricsRecord(ClientMetricsEndpointType.Token, callState);
            }
        }
        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);
            }
        }
예제 #4
0
        public AuthorizationResult ProcessAuthorizationResult(IWebAuthenticationBrokerContinuationEventArgs args, CallState callState)
        {
            AuthorizationResult result;

            switch (args.WebAuthenticationResult.ResponseStatus)
            {
            case WebAuthenticationStatus.Success:
                result = OAuth2Response.ParseAuthorizeResponse(args.WebAuthenticationResult.ResponseData, callState);
                break;

            case WebAuthenticationStatus.ErrorHttp:
                result = new AuthorizationResult(AdalError.AuthenticationFailed, args.WebAuthenticationResult.ResponseErrorDetail.ToString());
                break;

            case WebAuthenticationStatus.UserCancel:
                result = new AuthorizationResult(AdalError.AuthenticationCanceled, AdalErrorMessage.AuthenticationCanceled);
                break;

            default:
                result = new AuthorizationResult(AdalError.AuthenticationFailed, AdalErrorMessage.AuthorizationServerInvalidResponse);
                break;
            }

            return(result);
        }
        private async Task <AuthenticationResult> SendHttpMessageAsync(RequestParameters requestParameters)
        {
            string uri = HttpHelper.CheckForExtraQueryParameter(this.Authenticator.TokenUri);

            TokenResponse tokenResponse = await HttpHelper.SendPostRequestAndDeserializeJsonResponseAsync <TokenResponse>(uri, requestParameters, this.CallState);

            return(OAuth2Response.ParseTokenResponse(tokenResponse, this.CallState));
        }
예제 #6
0
        private async Task <AuthenticationResult> SendHttpMessageAsync(RequestParameters requestParameters)
        {
            string uri = HttpHelper.CheckForExtraQueryParameter(this.Authenticator.TokenUri);

            TokenResponse tokenResponse = await HttpHelper.SendPostRequestAndDeserializeJsonResponseAsync <TokenResponse>(uri, requestParameters, this.CallState);

            AuthenticationResult result = OAuth2Response.ParseTokenResponse(tokenResponse, this.CallState);

            if (result.RefreshToken == null && requestParameters.ContainsKey(OAuthParameter.RefreshToken))
            {
                result.RefreshToken = requestParameters[OAuthParameter.RefreshToken];
                Logger.Verbose(this.CallState, "Refresh token was missing from the token refresh response, so the refresh token in the request is returned instead");
            }

            result.IsMultipleResourceRefreshToken = (!string.IsNullOrWhiteSpace(result.RefreshToken) && !string.IsNullOrWhiteSpace(tokenResponse.Resource));
            return(result);
        }
        internal void AcquireAuthorization()
        {
            var sendAuthorizeRequest = new Action(
                delegate
            {
                Uri authorizationUri     = this.CreateAuthorizationUri(IncludeFormsAuthParams());
                string resultUri         = this.webUi.Authenticate(authorizationUri, this.redirectUri);
                this.authorizationResult = OAuth2Response.ParseAuthorizeResponse(resultUri, this.CallState);
            });

            // If the thread is MTA, it cannot create or communicate with WebBrowser which is a COM control.
            // In this case, we have to create the browser in an STA thread via StaTaskScheduler object.
            if (Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA)
            {
                using (var staTaskScheduler = new StaTaskScheduler(1))
                {
                    Task.Factory.StartNew(sendAuthorizeRequest, CancellationToken.None, TaskCreationOptions.None, staTaskScheduler).Wait();
                }
            }
            else
            {
                sendAuthorizeRequest();
            }
        }