public void AsHttpResponseMessage()
        {
            var responseContent = new byte[10];

            (new Random()).NextBytes(responseContent);
            var responseStream   = new MemoryStream(responseContent);
            var outgoingResponse = new OutgoingWebResponse();

            outgoingResponse.Headers.Add("X-SOME-HEADER", "value");
            outgoingResponse.Headers.Add("Content-Length", responseContent.Length.ToString(CultureInfo.InvariantCulture));
            outgoingResponse.ResponseStream = responseStream;

            var httpResponseMessage = outgoingResponse.AsHttpResponseMessage();

            Assert.That(httpResponseMessage, Is.Not.Null);
            Assert.That(httpResponseMessage.Headers.GetValues("X-SOME-HEADER").ToList(), Is.EqualTo(new[] { "value" }));
            Assert.That(
                httpResponseMessage.Content.Headers.GetValues("Content-Length").ToList(),
                Is.EqualTo(new[] { responseContent.Length.ToString(CultureInfo.InvariantCulture) }));
            var actualContent = new byte[responseContent.Length + 1];             // give the opportunity to provide a bit more data than we expect.
            var bytesRead     = httpResponseMessage.Content.ReadAsStreamAsync().Result.Read(actualContent, 0, actualContent.Length);

            Assert.That(bytesRead, Is.EqualTo(responseContent.Length));             // verify that only the data we expected came back.
            var trimmedActualContent = new byte[bytesRead];

            Array.Copy(actualContent, trimmedActualContent, bytesRead);
            Assert.That(trimmedActualContent, Is.EqualTo(responseContent));
        }
Exemplo n.º 2
0
        public Uri RequestUserAuthorization(IDictionary <string, string> requestParameters, IDictionary <string, string> redirectParameters, out string requestToken)
        {
            var message = this.PrepareRequestUserAuthorization(null, requestParameters, redirectParameters, out requestToken);
            OutgoingWebResponse response = this.Channel.PrepareResponse(message);

            return(response.GetDirectUriRequest(this.Channel));
        }
Exemplo n.º 3
0
        /// <summary>
        ///     Handle the request to authorize the request
        /// </summary>
        /// <param name="request">The request to handle</param>
        /// <param name="jsonRequest">The parameters of the call, if JSON request</param>
        public DnoaAuthZResponse HandleTokenRequest(IRequest request, CreateAccessToken jsonRequest)
        {
            OutgoingWebResponse response = GetResponse(request, jsonRequest);

            var responseBody = response.Body.FromJson <Dictionary <string, string> >();

            if (response.Status == HttpStatusCode.OK)
            {
                return(new DnoaAuthZResponse
                {
                    AccessToken = responseBody[@"access_token"],
                    RefreshToken = responseBody[@"refresh_token"],
                    ExpiresIn = responseBody[@"expires_in"],
                    TokenType = responseBody[@"token_type"],
                    Scope = responseBody[@"scope"],
                });
            }

            string error   = (responseBody.ContainsKey(@"error")) ? responseBody[@"error"] : string.Empty;
            string message = (responseBody.ContainsKey(@"error_description"))
                ? responseBody[@"error_description"]
                : error;

            throw LogicErrorThrower.RuleViolation(message);
        }
Exemplo n.º 4
0
        private IAuthorizationState GetAuthorization(WebServerClient client)
        {
            // If this user is already authenticated, then just return the auth state.
            IAuthorizationState state = AuthState;

            if (state != null)
            {
                return(state);
            }

            // Check if an authorization request already is in progress.
            state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
            if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken)))
            {
                // Store and return the credentials.
                HttpContext.Current.Session["AUTH_STATE"] = _state = state;
                return(state);
            }

            // Otherwise do a new authorization request.
            string scope = TasksService.Scopes.TasksReadonly.GetStringValue();
            OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope }, "");

            response.Send(); // Will throw a ThreadAbortException to prevent sending another response.
            return(null);
        }
Exemplo n.º 5
0
        public void SendIndirectMessageFormPost()
        {
            // We craft a very large message to force fallback to form POST.
            // We'll also stick some HTML reserved characters in the string value
            // to test proper character escaping.
            var message = new TestDirectedMessage(MessageTransport.Indirect)
            {
                Age       = 15,
                Name      = "c<b" + new string('a', 10 * 1024),
                Location  = new Uri("http://host/path"),
                Recipient = new Uri("http://provider/path"),
            };
            OutgoingWebResponse response = this.Channel.PrepareResponse(message);

            Assert.AreEqual(HttpStatusCode.OK, response.Status, "A form redirect should be an HTTP successful response.");
            Assert.IsNull(response.Headers[HttpResponseHeader.Location], "There should not be a redirection header in the response.");
            string body = response.Body;

            StringAssert.Contains("<form ", body);
            StringAssert.Contains("action=\"http://provider/path\"", body);
            StringAssert.Contains("method=\"post\"", body);
            StringAssert.Contains("<input type=\"hidden\" name=\"age\" value=\"15\" />", body);
            StringAssert.Contains("<input type=\"hidden\" name=\"Location\" value=\"http://host/path\" />", body);
            StringAssert.Contains("<input type=\"hidden\" name=\"Name\" value=\"" + HttpUtility.HtmlEncode(message.Name) + "\" />", body);
            StringAssert.Contains(".submit()", body, "There should be some javascript to automate form submission.");
        }
Exemplo n.º 6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Request.IsSecureConnection)
        {
            throw new HttpException((int)HttpStatusCode.Forbidden, "Authorization requests MUST be on a secure channel");
        }

        if (String.IsNullOrEmpty(Request.PathInfo))
        {
            AuthorizationServer authorizationServer = new AuthorizationServer(new OAuth2AuthorizationServer());
            OutgoingWebResponse wr = authorizationServer.HandleTokenRequest();
            Response.Clear();
            Response.ContentType = "application/json; charset=utf-8";
            Response.Write(wr.Body);
            Response.End();
        }
        else
        {
            using (OAuthServiceCall service = new OAuthServiceCall(Request))
            {
                Response.Clear();
                Response.ContentType = service.ContentType;
                service.Execute(Response.OutputStream);
                Response.End();
            }
        }
    }
        private OutgoingWebResponse AwaitIncomingRawResponse()
        {
            this.IncomingMessageSignal.WaitOne();
            OutgoingWebResponse response = this.IncomingRawResponse;

            this.IncomingRawResponse = null;
            return(response);
        }
Exemplo n.º 8
0
    protected void RejectWithError(string szError)
    {
        EndUserAuthorizationFailedResponse resp = authorizationServer.PrepareRejectAuthorizationRequest(m_pendingRequest);

        resp.Error = szError;
        OutgoingWebResponse wr = authorizationServer.Channel.PrepareResponse(resp);

        wr.Send();
    }
Exemplo n.º 9
0
        public ActionResult Index()
        {
            // Have the authorization server handle the token request.
            // It will use the passed-in request to determine what the actual token request is.
            // If the request does not contain a valid token request, an exception is thrown
            OutgoingWebResponse outgoingWebResponse = this.authorizationServer.HandleTokenRequest(this.Request);

            // Convert the outgoing web response to an ActionResult to correctly integrate with ASP.NET MVC flow
            return(outgoingWebResponse.AsActionResult());
        }
Exemplo n.º 10
0
        /// <summary>
        /// Queues a message for sending in the response stream.
        /// </summary>
        /// <param name="response">The message to send as a response.</param>
        /// <returns>
        /// The pending user agent redirect based message to be sent as an HttpResponse.
        /// </returns>
        /// <remarks>
        /// This method implements spec OAuth V1.0 section 5.3.
        /// </remarks>
        protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response)
        {
            var webResponse = new OutgoingWebResponse();

            ApplyMessageTemplate(response, webResponse);
            string json = this.SerializeAsJson(response);

            webResponse.SetResponse(json, new ContentType(JsonEncoded));
            return(webResponse);
        }
Exemplo n.º 11
0
 /// <summary>
 /// The OAuth 2.0 token endpoint.
 /// </summary>
 /// <returns>The response to the Client.</returns>
 public ActionResult Token()
 {
     using (OAuth2AuthorizationServer server = (new OAuth2AuthorizationServer(new X509Certificate2(ConfigurationManager.AppSettings["AbsolutePathToPfx"], ConfigurationManager.AppSettings["CertificatePassword"]),
                                                                              new X509Certificate2(ConfigurationManager.AppSettings["AbsolutePathToCertificate"]))))
     {
         AuthorizationServer authorizationServer = new AuthorizationServer(server);
         OutgoingWebResponse response            = authorizationServer.HandleTokenRequest(this.Request);
         return(response.AsActionResult());
     }
 }
Exemplo n.º 12
0
		public void SendDirectMessageResponseHonorsHttpStatusCodes() {
			IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired);
			OutgoingWebResponse directResponse = this.channel.PrepareDirectResponseTestHook(message);
			Assert.AreEqual(HttpStatusCode.OK, directResponse.Status);

			var httpMessage = new TestDirectResponseMessageWithHttpStatus();
			MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired, httpMessage);
			httpMessage.HttpStatusCode = HttpStatusCode.NotAcceptable;
			directResponse = this.channel.PrepareDirectResponseTestHook(httpMessage);
			Assert.AreEqual(HttpStatusCode.NotAcceptable, directResponse.Status);
		}
Exemplo n.º 13
0
        public void AsHttpResponseMessageNoContent()
        {
            var outgoingResponse = new OutgoingWebResponse();

            outgoingResponse.Headers.Add("X-SOME-HEADER", "value");

            var httpResponseMessage = outgoingResponse.AsHttpResponseMessage();

            Assert.That(httpResponseMessage, Is.Not.Null);
            Assert.That(httpResponseMessage.Headers.GetValues("X-SOME-HEADER").ToList(), Is.EqualTo(new[] { "value" }));
            Assert.That(httpResponseMessage.Content, Is.Null);
        }
        /// <summary>
        /// Serializes the results of discovery and the created auth requests as a JSON object
        /// for the user agent to initiate.
        /// </summary>
        /// <param name="identifier">The identifier to perform discovery on.</param>
        /// <returns>The JSON string.</returns>
        private string SerializeDiscoveryAsJson(Identifier identifier)
        {
            ErrorUtilities.VerifyArgumentNotNull(identifier, "identifier");

            // We prepare a JSON object with this interface:
            // class jsonResponse {
            //    string claimedIdentifier;
            //    Array requests; // never null
            //    string error; // null if no error
            // }
            // Each element in the requests array looks like this:
            // class jsonAuthRequest {
            //    string endpoint;  // URL to the OP endpoint
            //    string immediate; // URL to initiate an immediate request
            //    string setup;     // URL to initiate a setup request.
            // }
            StringBuilder discoveryResultBuilder = new StringBuilder();

            discoveryResultBuilder.Append("{");
            try {
                IEnumerable <IAuthenticationRequest> requests = this.CreateRequests(identifier).CacheGeneratedResults();
                if (requests.Any())
                {
                    discoveryResultBuilder.AppendFormat("claimedIdentifier: {0},", MessagingUtilities.GetSafeJavascriptValue(requests.First().ClaimedIdentifier));
                    discoveryResultBuilder.Append("requests: [");
                    foreach (IAuthenticationRequest request in requests)
                    {
                        discoveryResultBuilder.Append("{");
                        discoveryResultBuilder.AppendFormat("endpoint: {0},", MessagingUtilities.GetSafeJavascriptValue(request.Provider.Uri.AbsoluteUri));
                        request.Mode = AuthenticationRequestMode.Immediate;
                        OutgoingWebResponse response = request.RedirectingResponse;
                        discoveryResultBuilder.AppendFormat("immediate: {0},", MessagingUtilities.GetSafeJavascriptValue(response.GetDirectUriRequest(this.RelyingParty.Channel).AbsoluteUri));
                        request.Mode = AuthenticationRequestMode.Setup;
                        response     = request.RedirectingResponse;
                        discoveryResultBuilder.AppendFormat("setup: {0}", MessagingUtilities.GetSafeJavascriptValue(response.GetDirectUriRequest(this.RelyingParty.Channel).AbsoluteUri));
                        discoveryResultBuilder.Append("},");
                    }
                    discoveryResultBuilder.Length -= 1;                     // trim off last comma
                    discoveryResultBuilder.Append("]");
                }
                else
                {
                    discoveryResultBuilder.Append("requests: [],");
                    discoveryResultBuilder.AppendFormat("error: {0}", MessagingUtilities.GetSafeJavascriptValue(OpenIdStrings.OpenIdEndpointNotFound));
                }
            } catch (ProtocolException ex) {
                discoveryResultBuilder.Append("requests: [],");
                discoveryResultBuilder.AppendFormat("error: {0}", MessagingUtilities.GetSafeJavascriptValue(ex.Message));
            }

            discoveryResultBuilder.Append("}");
            return(discoveryResultBuilder.ToString());
        }
        private ActionResult InitAuthentication()
        {
            AuthorizationState state = new AuthorizationState();
            string             uri   = Request.Url.AbsoluteUri;

            uri            = RemoveQueryStringFromUri(uri);
            state.Callback = new Uri(uri);

            OutgoingWebResponse response = client.PrepareRequestUserAuthorization(state);

            return(response.AsActionResultMvc5());
        }
        /// <summary>
        /// Gets the authorization object for the client-side flow.
        /// </summary>
        /// <param name="client">The client used for authorization.
        /// </param>
        /// <returns>An authorization state that can be used for API queries.
        /// </returns>
        protected IAuthorizationState GetAuthorization(WebServerClient client)
        {
            // If we don't yet have user, use the client to perform
            // authorization.
            if (_authState != null)
            {
                HttpRequestInfo reqinfo = null;
                if (_httpReqMethod != null && _reqUri != null && _rawUrl != null &&
                    _headers != null && _inputStream != null)
                {
                    reqinfo = new HttpRequestInfo(_httpReqMethod, _reqUri, _rawUrl,
                                                  (System.Net.WebHeaderCollection)_headers, _inputStream);
                }

                if (reqinfo == null)
                {
                    reqinfo = new HttpRequestInfo(HttpContext.Current.Request);
                }
                client.ProcessUserAuthorization(reqinfo);
            }

            // Check for a cached session state.
            if (_authState == null)
            {
                _authState = (IAuthorizationState)HttpContext.Current.
                             Session["AUTH_STATE"];
            }

            // Check if we need to refresh the authorization state and refresh
            // it if necessary.
            if (_authState != null)
            {
                if (_authState.RefreshToken.IsNotNullOrEmpty() && (_authState.AccessToken == null ||
                                                                   DateTime.UtcNow > _authState.AccessTokenExpirationUtc))
                {
                    client.RefreshToken(_authState);
                }
                return(_authState);
            }

            // If we fall through to here, perform an authorization request.
            OutgoingWebResponse response =
                client.PrepareRequestUserAuthorization();

            response.Send();
            // Note: response.send will throw a ThreadAbortException to
            // prevent sending another response.
            return(null);
        }
Exemplo n.º 17
0
        public void DirectResponsesSentUsingKeyValueForm()
        {
            IProtocolMessage  message       = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired);
            MessageDictionary messageFields = this.MessageDescriptions.GetAccessor(message);

            byte[] expectedBytes       = KeyValueFormEncoding.GetBytes(messageFields);
            string expectedContentType = OpenIdChannel.KeyValueFormContentType;

            OutgoingWebResponse directResponse = this.channel.PrepareDirectResponseTestHook(message);

            Assert.AreEqual(expectedContentType, directResponse.Headers[HttpResponseHeader.ContentType]);
            byte[] actualBytes = new byte[directResponse.ResponseStream.Length];
            directResponse.ResponseStream.Read(actualBytes, 0, actualBytes.Length);
            Assert.IsTrue(MessagingUtilities.AreEquivalent(expectedBytes, actualBytes));
        }
        /// <summary>
        /// Notifies the user agent via an AJAX response of a completed authentication attempt.
        /// </summary>
        protected override void ScriptClosingPopupOrIFrame()
        {
            Action <AuthenticationStatus> callback = status => {
                if (status == AuthenticationStatus.Authenticated)
                {
                    this.OnUnconfirmedPositiveAssertion();                     // event handler will fill the clientScriptExtensions collection.
                }
            };

            OutgoingWebResponse response = this.RelyingParty.ProcessResponseFromPopup(
                this.RelyingParty.Channel.GetRequestFromContext(),
                callback);

            response.Send();
        }
Exemplo n.º 19
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Request.IsSecureConnection)
            {
                throw new HttpException((int)HttpStatusCode.Forbidden, "Authorization requests MUST be on a secure channel");
            }

            if (String.IsNullOrEmpty(Request.PathInfo))
            {
                AuthorizationServer authorizationServer = new AuthorizationServer(new OAuth2AuthorizationServer());
                OutgoingWebResponse wr = authorizationServer.HandleTokenRequest();
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.Write(wr.Body);
                Response.End();
            }
            else
            {
                using (OAuthServiceCall service = new OAuthServiceCall(Request))
                {
                    Response.Clear();
                    Response.ContentType = service.ContentType;
                    service.Execute(Response.OutputStream);
                    Response.End();
                }
            }
        }
        catch (Exception ex)
        {
            var o = Request.Params["dbg"];
            if (o != null)
            {
                Response.Clear();
                Response.ContentType     = "text/plain";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.Write("Error: " + ex.Message + "\r\n");
                Response.Write(ex.ToStringDescriptive() + "\r\n");
                Response.Flush();
                Response.End();
            }
            else
            {
                throw;
            }
        }
    }
Exemplo n.º 20
0
        /// <summary>
        /// Queues a message for sending in the response stream where the fields
        /// are sent in the response stream in querystring style.
        /// </summary>
        /// <param name="response">The message to send as a response.</param>
        /// <returns>The pending user agent redirect based message to be sent as an HttpResponse.</returns>
        /// <remarks>
        /// This method implements spec V1.0 section 5.3.
        /// </remarks>
        protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response)
        {
            var    messageAccessor = this.MessageDescriptions.GetAccessor(response);
            var    fields          = messageAccessor.Serialize();
            string responseBody    = MessagingUtilities.CreateQueryString(fields);

            OutgoingWebResponse encodedResponse = new OutgoingWebResponse {
                Body            = responseBody,
                OriginalMessage = response,
                Status          = HttpStatusCode.OK,
                Headers         = new System.Net.WebHeaderCollection(),
            };

            ApplyMessageTemplate(response, encodedResponse);
            return(encodedResponse);
        }
Exemplo n.º 21
0
        public void SpecAppendixAExample()
        {
            ServiceProviderDescription serviceDescription = new ServiceProviderDescription()
            {
                RequestTokenEndpoint      = new MessageReceivingEndpoint("https://photos.example.net/request_token", HttpDeliveryMethods.PostRequest),
                UserAuthorizationEndpoint = new MessageReceivingEndpoint("http://photos.example.net/authorize", HttpDeliveryMethods.GetRequest),
                AccessTokenEndpoint       = new MessageReceivingEndpoint("https://photos.example.net/access_token", HttpDeliveryMethods.PostRequest),
                TamperProtectionElements  = new ITamperProtectionChannelBindingElement[] {
                    new PlaintextSigningBindingElement(),
                    new HmacSha1SigningBindingElement(),
                },
            };
            MessageReceivingEndpoint accessPhotoEndpoint = new MessageReceivingEndpoint("http://photos.example.net/photos?file=vacation.jpg&size=original", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest);
            ConsumerDescription      consumerDescription = new ConsumerDescription("dpf43f3p2l4k3l03", "kd94hf93k423kf44");

            OAuthCoordinator coordinator = new OAuthCoordinator(
                consumerDescription,
                serviceDescription,
                consumer => {
                consumer.Channel.PrepareResponse(consumer.PrepareRequestUserAuthorization(new Uri("http://printer.example.com/request_token_ready"), null, null));                         // .Send() dropped because this is just a simulation
                string accessToken = consumer.ProcessUserAuthorization().AccessToken;
                var photoRequest   = consumer.CreateAuthorizingMessage(accessPhotoEndpoint, accessToken);
                OutgoingWebResponse protectedPhoto = ((CoordinatingOAuthChannel)consumer.Channel).RequestProtectedResource(photoRequest);
                Assert.IsNotNull(protectedPhoto);
                Assert.AreEqual(HttpStatusCode.OK, protectedPhoto.Status);
                Assert.AreEqual("image/jpeg", protectedPhoto.Headers[HttpResponseHeader.ContentType]);
                Assert.AreNotEqual(0, protectedPhoto.ResponseStream.Length);
            },
                sp => {
                var requestTokenMessage = sp.ReadTokenRequest();
                sp.Channel.PrepareResponse(sp.PrepareUnauthorizedTokenMessage(requestTokenMessage));                         // .Send() dropped because this is just a simulation
                var authRequest = sp.ReadAuthorizationRequest();
                ((InMemoryTokenManager)sp.TokenManager).AuthorizeRequestToken(authRequest.RequestToken);
                sp.Channel.PrepareResponse(sp.PrepareAuthorizationResponse(authRequest));                        // .Send() dropped because this is just a simulation
                var accessRequest = sp.ReadAccessTokenRequest();
                sp.Channel.PrepareResponse(sp.PrepareAccessTokenMessage(accessRequest));                         // .Send() dropped because this is just a simulation
                string accessToken = sp.ReadProtectedResourceAuthorization().AccessToken;
                ((CoordinatingOAuthChannel)sp.Channel).SendDirectRawResponse(new OutgoingWebResponse {
                    ResponseStream = new MemoryStream(new byte[] { 0x33, 0x66 }),
                    Headers        = new WebHeaderCollection {
                        { HttpResponseHeader.ContentType, "image/jpeg" },
                    },
                });
            });

            coordinator.Run();
        }
Exemplo n.º 22
0
		public void SendDirectMessageResponse() {
			IProtocolMessage message = new TestDirectedMessage {
				Age = 15,
				Name = "Andrew",
				Location = new Uri("http://hostb/pathB"),
			};

			OutgoingWebResponse response = this.channel.PrepareResponse(message);
			Assert.AreSame(message, response.OriginalMessage);
			Assert.AreEqual(HttpStatusCode.OK, response.Status);
			Assert.AreEqual(2, response.Headers.Count);

			NameValueCollection body = HttpUtility.ParseQueryString(response.Body);
			Assert.AreEqual("15", body["age"]);
			Assert.AreEqual("Andrew", body["Name"]);
			Assert.AreEqual("http://hostb/pathB", body["Location"]);
		}
Exemplo n.º 23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Request.IsSecureConnection)
            {
                throw new HttpException((int)HttpStatusCode.Forbidden, "Authorization requests MUST be on a secure channel");
            }

            if (String.IsNullOrEmpty(Request.PathInfo))
            {
                AuthorizationServer authorizationServer = new AuthorizationServer(new OAuth2AuthorizationServer());
                OutgoingWebResponse wr = authorizationServer.HandleTokenRequest();
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.Write(wr.Body);
                HttpContext.Current.Response.Flush();                      // Sends all currently buffered output to the client.
                HttpContext.Current.Response.SuppressContent = true;       // Gets or sets a value indicating whether to send HTTP content to the client.
                HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
            }
            else
            {
                using (OAuthServiceCall service = new OAuthServiceCall(Request))
                {
                    Response.Clear();
                    Response.ContentType = service.ContentType;
                    service.Execute(Response.OutputStream);
                    HttpContext.Current.Response.Flush();                      // Sends all currently buffered output to the client.
                    HttpContext.Current.Response.SuppressContent = true;       // Gets or sets a value indicating whether to send HTTP content to the client.
                    HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
                }
            }
        }
        catch (Exception ex)
        {
            Response.Clear();
            Response.ContentType     = "text/plain";
            Response.StatusCode      = (int)HttpStatusCode.InternalServerError;
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.Write("Error: " + ex.Message + "\r\n");
            Response.Write(ex.ToStringDescriptive() + "\r\n");
            Response.Flush();
            Response.End();
        }
    }
Exemplo n.º 24
0
        public void SetBodyToByteStream()
        {
            var    response    = new OutgoingWebResponse();
            string stringValue = "abc";

            response.Body = stringValue;
            Assert.AreEqual(stringValue.Length, response.ResponseStream.Length);

            // Verify that the actual bytes are correct.
            Encoding encoding       = new UTF8Encoding(false);       // avoid emitting a byte-order mark
            var      expectedBuffer = encoding.GetBytes(stringValue);
            var      actualBuffer   = new byte[stringValue.Length];

            Assert.AreEqual(stringValue.Length, response.ResponseStream.Read(actualBuffer, 0, stringValue.Length));
            CollectionAssert.AreEqual(expectedBuffer, actualBuffer);

            // Verify that the header was set correctly.
            Assert.IsNull(response.Headers[HttpResponseHeader.ContentEncoding]);
            Assert.AreEqual(encoding.HeaderName, new ContentType(response.Headers[HttpResponseHeader.ContentType]).CharSet);
        }
Exemplo n.º 25
0
        public void SendIndirectMessage301Get()
        {
            TestDirectedMessage message = new TestDirectedMessage(MessageTransport.Indirect);

            GetStandardTestMessage(FieldFill.CompleteBeforeBindings, message);
            message.Recipient = new Uri("http://provider/path");
            var expected = GetStandardTestFields(FieldFill.CompleteBeforeBindings);

            OutgoingWebResponse response = this.Channel.PrepareResponse(message);

            Assert.AreEqual(HttpStatusCode.Redirect, response.Status);
            StringAssert.StartsWith("http://provider/path", response.Headers[HttpResponseHeader.Location]);
            foreach (var pair in expected)
            {
                string key       = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Key);
                string value     = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Value);
                string substring = string.Format("{0}={1}", key, value);
                StringAssert.Contains(substring, response.Headers[HttpResponseHeader.Location]);
            }
        }
Exemplo n.º 26
0
        public void Respond()
        {
            StringWriter writer       = new StringWriter();
            HttpRequest  httpRequest  = new HttpRequest("file", "http://server", string.Empty);
            HttpResponse httpResponse = new HttpResponse(writer);
            HttpContext  context      = new HttpContext(httpRequest, httpResponse);

            HttpContext.Current = context;

            OutgoingWebResponse response = new OutgoingWebResponse();

            response.Status = System.Net.HttpStatusCode.OK;
            response.Headers["someHeaderName"] = "someHeaderValue";
            response.Body = "some body";
            response.Respond();
            string results = writer.ToString();

            // For some reason the only output in test is the body... the headers require a web host
            Assert.AreEqual(response.Body, results);
        }
Exemplo n.º 27
0
        public void SendIndirectMessage301Get()
        {
            TestDirectedMessage message = new TestDirectedMessage(MessageTransport.Indirect);

            GetStandardTestMessage(FieldFill.CompleteBeforeBindings, message);
            message.Recipient = new Uri("http://provider/path");
            var expected = GetStandardTestFields(FieldFill.CompleteBeforeBindings);

            OutgoingWebResponse response = this.Channel.PrepareResponse(message);

            Assert.AreEqual(HttpStatusCode.Redirect, response.Status);
            Assert.AreEqual("text/html; charset=utf-8", response.Headers[HttpResponseHeader.ContentType]);
            Assert.IsTrue(response.Body != null && response.Body.Length > 0);             // a non-empty body helps get passed filters like WebSense
            StringAssert.StartsWith("http://provider/path", response.Headers[HttpResponseHeader.Location]);
            foreach (var pair in expected)
            {
                string key       = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Key);
                string value     = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Value);
                string substring = string.Format("{0}={1}", key, value);
                StringAssert.Contains(substring, response.Headers[HttpResponseHeader.Location]);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Queues a message for sending in the response stream where the fields
        /// are sent in the response stream in querystring style.
        /// </summary>
        /// <param name="response">The message to send as a response.</param>
        /// <returns>
        /// The pending user agent redirect based message to be sent as an HttpResponse.
        /// </returns>
        /// <remarks>
        /// This method implements spec OAuth V1.0 section 5.3.
        /// </remarks>
        protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response)
        {
            var webResponse = new OutgoingWebResponse();

            // The only direct response from a resource server is some authorization error (400, 401, 403).
            var unauthorizedResponse = response as UnauthorizedResponse;

            ErrorUtilities.VerifyInternal(unauthorizedResponse != null, "Only unauthorized responses are expected.");

            // First initialize based on the specifics within the message.
            ApplyMessageTemplate(response, webResponse);
            if (!(response is IHttpDirectResponse))
            {
                webResponse.Status = HttpStatusCode.Unauthorized;
            }

            // Now serialize all the message parts into the WWW-Authenticate header.
            var fields = this.MessageDescriptions.GetAccessor(response);

            webResponse.Headers[HttpResponseHeader.WwwAuthenticate] = MessagingUtilities.AssembleAuthorizationHeader(unauthorizedResponse.Scheme, fields);
            return(webResponse);
        }
Exemplo n.º 29
0
    protected void btnYes_Click(object sender, EventArgs e)
    {
        if (m_pendingRequest == null)
        {
            throw new HttpException((int)HttpStatusCode.BadRequest, Resources.LocalizedText.oAuthErrMissingRequest);
        }

        MFBOauthClientAuth ca = new MFBOauthClientAuth {
            Scope = OAuthUtilities.JoinScopes(m_pendingRequest.Scope), ClientId = m_pendingRequest.ClientIdentifier, UserId = Page.User.Identity.Name, ExpirationDateUtc = DateTime.UtcNow.AddDays(14)
        };

        if (ca.fCommit())
        {
            EndUserAuthorizationSuccessResponseBase resp = authorizationServer.PrepareApproveAuthorizationRequest(m_pendingRequest, Page.User.Identity.Name);
            OutgoingWebResponse wr = authorizationServer.Channel.PrepareResponse(resp);
            wr.Send();
        }
        else
        {
            RejectWithError(Resources.LocalizedText.oAuthErrCreationFailed);
        }
    }
Exemplo n.º 30
0
        /// <summary>
        /// Queues a message for sending in the response stream where the fields
        /// are sent in the response stream in querystring style.
        /// </summary>
        /// <param name="response">The message to send as a response.</param>
        /// <returns>
        /// The pending user agent redirect based message to be sent as an HttpResponse.
        /// </returns>
        /// <remarks>
        /// This method implements spec V1.0 section 5.3.
        /// </remarks>
        protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response)
        {
            var messageAccessor = this.MessageDescriptions.GetAccessor(response);
            var fields          = messageAccessor.Serialize();

            byte[] keyValueEncoding = KeyValueFormEncoding.GetBytes(fields);

            OutgoingWebResponse preparedResponse = new OutgoingWebResponse();

            preparedResponse.Headers.Add(HttpResponseHeader.ContentType, KeyValueFormContentType);
            preparedResponse.OriginalMessage = response;
            preparedResponse.ResponseStream  = new MemoryStream(keyValueEncoding);

            IHttpDirectResponse httpMessage = response as IHttpDirectResponse;

            if (httpMessage != null)
            {
                preparedResponse.Status = httpMessage.HttpStatusCode;
            }

            return(preparedResponse);
        }