Пример #1
0
        private string CallService(string url)
        {
            if (Authorization == null)
            {
                throw new InvalidOperationException("No access token!");
            }

            if (Authorization.AccessTokenExpirationUtc.HasValue)
            {
                // 刷新access token
                Client.RefreshAuthorizationAsync(Authorization, TimeSpan.FromSeconds(30));
            }

            var httpRequest = (HttpWebRequest)WebRequest.Create(url);

            ClientBase.AuthorizeRequest(httpRequest, Authorization.AccessToken);
            var    response = httpRequest.GetResponse();
            string result   = "";

            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }

            return(result);
        }
Пример #2
0
        public override void ApplyAuthenticationToRequest(HttpWebRequest request)
        {
            base.ApplyAuthenticationToRequest(request);

            // Populate the AuthorizationState with an access token.
            LoadAccessToken();
            try
            {
                if (State != null && !string.IsNullOrEmpty(State.AccessToken))
                {
                    // Apply authorization to the current request
                    if (string.IsNullOrEmpty(State.RefreshToken))
                    {
                        ClientBase.AuthorizeRequest(request, State.AccessToken);
                    }
                    else
                    {
                        // This only works if State has a refresh token
                        tokenProvider.AuthorizeRequest(request, State);
                    }
                }
            }
            finally
            {
                if (NoCaching)
                {
                    State = null;
                }
            }
        }
Пример #3
0
        public void ApplyAuthenticationToRequest(HttpWebRequest request)
        {
            // Turn off Expect100Continue behavior. For web method calls it is not used
            // and many servers reject the request if this is present on PUT or POST
            // requests with a body present. If used, Expect100Continue prevents the client
            // from sending the request body unless the server approves the request by sending
            // Expect100Continue.
            request.ServicePoint.Expect100Continue = false;

            // Populate the AuthorizationState with an access token.
            LoadAccessToken();
            try
            {
                if (State != null && !string.IsNullOrEmpty(State.AccessToken))
                {
                    // Apply authorization to the current request
                    if (string.IsNullOrEmpty(State.RefreshToken))
                    {
                        ClientBase.AuthorizeRequest(request, State.AccessToken);
                    }
                    else
                    {
                        // This only works if State has a refresh token
                        tokenProvider.AuthorizeRequest(request, State);
                    }
                }
            }
            finally
            {
                if (NoCaching)
                {
                    State = null;
                }
            }
        }
Пример #4
0
        private void getResourceButton_Click(object sender, EventArgs e)
        {
            var sb = new StringBuilder();

            // Create the ServiceStack API client and the request DTO
            var apiClient     = new JsonServiceClient(resourceUriTextBox.Text);
            var apiRequestDto = new Users {
                Username = usernameTextBox.Text
            };

            // Wire up the ServiceStack client filter so that DotNetOpenAuth can
            // add the authorization header before the request is sent
            // to the API server
            apiClient.LocalHttpWebRequestFilter = request => {
                // This is the magic line that makes all the client-side magic work :)
                ClientBase.AuthorizeRequest(request, accessTokenTextBox.Text);

                LogStuff(request, sb);
            };
            // This filter is used only for logging the response output. The code will work without it.
            apiClient.LocalHttpWebResponseFilter += response => LogStuff(response, sb);

            try {
                // Send the API request and dump the response to our output TextBox
                var response = apiClient.Get(apiRequestDto);
                LogStuff(response, sb);
            } catch (WebServiceException ex) {
                sb.AppendLine(ex.Dump());
                sb.AppendLine(ex.ResponseBody.Replace(" at ", Environment.NewLine + "   at "));
            } catch (Exception ex) {
                sb.AppendLine(ex.Message);
            }
            outputTextBox.Text = sb.ToString();
        }
Пример #5
0
        private async Task <T> CallServiceAsync <T>(Func <DataApiClient, T> predicate, CancellationToken cancellationToken)
        {
            if (Authorization == null)
            {
                throw new InvalidOperationException("No access token!");
            }

            var wcfClient = new DataApiClient();

            // Refresh the access token if it expires and if its lifetime is too short to be of use.
            if (Authorization.AccessTokenExpirationUtc.HasValue)
            {
                if (await Client.RefreshAuthorizationAsync(Authorization, TimeSpan.FromSeconds(30)))
                {
                    TimeSpan timeLeft = Authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow;
                    this.authorizationLabel.Text += string.Format(CultureInfo.CurrentCulture, " - just renewed for {0} more minutes)", Math.Round(timeLeft.TotalMinutes, 1));
                }
            }

            var httpRequest = (HttpWebRequest)WebRequest.Create(wcfClient.Endpoint.Address.Uri);

            ClientBase.AuthorizeRequest(httpRequest, Authorization.AccessToken);

            var httpDetails = new HttpRequestMessageProperty();

            httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization];
            using (var scope = new OperationContextScope(wcfClient.InnerChannel)) {
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;
                return(predicate(wcfClient));
            }
        }
Пример #6
0
        protected async void Button1_Click(object sender, EventArgs e)
        {
            var authServer = new AuthorizationServerDescription()
            {
                TokenEndpoint   = new Uri("http://localhost:53022/OAuth/token "),
                ProtocolVersion = ProtocolVersion.V20
            };
            WebServerClient Client = new WebServerClient(authServer, "idefav", "1");

            var code = await Client.GetClientAccessTokenAsync(new string[] { "http://localhost:55045/IService1/DoWork" });

            string token = code.AccessToken;

            Service1Reference.Service1Client service1Client = new Service1Client();
            var httpRequest = (HttpWebRequest)WebRequest.Create(service1Client.Endpoint.Address.Uri);

            ClientBase.AuthorizeRequest(httpRequest, token);
            var httpDetails = new HttpRequestMessageProperty();

            httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization];

            using (var scope = new OperationContextScope(service1Client.InnerChannel))
            {
                if (OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name))
                {
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;
                }
                else
                {
                    OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpDetails);
                }

                Button1.Text = service1Client.DoWork();
            }
        }
Пример #7
0
        /// <summary>
        /// Request the resource data from the web service instance. (Places the access token into the request header).
        /// </summary>
        /// <typeparam name="T">The return type of the service method.</typeparam>
        /// <typeparam name="TService">The web service type.</typeparam>
        /// <typeparam name="TServiceChannel">The web service interface channel.</typeparam>
        /// <param name="state">Provides access to a persistent object that tracks the state of an authorization.</param>
        /// <param name="resourceEndPointUrl">The resource endpoint url.</param>
        /// <param name="serviceInstance">The instance of the web service client.</param>
        /// <param name="predicate">The web service method action to execute.</param>
        /// <returns>The type of data to return from the action execution.</returns>
        public virtual T RequestResourceFromService <T, TService, TServiceChannel>(IAuthorizationState state, string resourceEndPointUrl, TService serviceInstance, Func <TService, T> predicate)
            where TService : ClientBase <TServiceChannel>
            where TServiceChannel : class
        {
            if (state == null)
            {
                throw new ArgumentNullException("state");
            }
            if (String.IsNullOrEmpty(resourceEndPointUrl))
            {
                throw new ArgumentNullException("resourceEndPointUrl");
            }
            if (serviceInstance == null)
            {
                throw new ArgumentNullException("serviceInstance");
            }
            if (predicate == null)
            {
                throw new ArgumentNullException("predicate");
            }

            // Create a new http request and add the access token
            // to the headers of the request.
            System.Net.HttpWebRequest httpRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(resourceEndPointUrl);
            ClientBase.AuthorizeRequest(httpRequest, state.AccessToken);

            // Add the headers of the request including the access token to the request details.
            HttpRequestMessageProperty httpDetails = new HttpRequestMessageProperty();

            httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization];

            // Create a new service scope context.
            using (OperationContextScope scope = new OperationContextScope(serviceInstance.InnerChannel))
            {
                // Add the headers including the access token
                // to the headers of the outgoing web service message.
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;

                // Execute the web service method action.
                return(predicate(serviceInstance));
            }
        }