public void authenticate(HttpListenerRequest req, HttpListenerResponse res, HTTPSession session) { // use the session object to store state between requests session["nonce"] = RandomString(); session["state"] = RandomString(); // TODO make authentication request // TODO insert the redirect URL string login_url = null; res.Redirect(login_url); res.Close(); }
public void Redirect(string url) { response.Redirect(url); }
/// <summary> /// Выполняет приложение /// Для запросов GET возвращает все записи. /// Для запросов POST создает и сохраняет новые записи. /// </summary> /// <param name="request">Request.</param> /// <param name="response">Response.</param> public override void Run(HttpListenerRequest request, HttpListenerResponse response) { if (request.HttpMethod == "POST") { if (request.HasEntityBody) { // читаем тело запроса string data = null; using (var reader = new StreamReader(request.InputStream)) { data = reader.ReadToEnd (); } if (!string.IsNullOrWhiteSpace(data)) { // формируем коллекцию параметров и их значений Dictionary<string, string> requestParams = new Dictionary<string, string>(); string[] prms = data.Split('&'); for (int i = 0; i < prms.Length; i++) { string[] pair = prms[i].Split('='); requestParams.Add(pair[0], Uri.UnescapeDataString(pair[1]).Replace('+',' ')); } SaveEntry (GuestbookEntry.FromDictionary(requestParams)); } response.Redirect(request.Url.ToString()); return; } } DisplayGuestbook (response); }
private void Respond(HttpListenerRequest request, HttpListenerResponse response, ResponsePacket resp) { // Are we redirecting? if (String.IsNullOrEmpty(resp.Redirect)) { // No redirect. // Do we have a response? if (resp.Data != null) { // Yes we do. response.ContentType = resp.ContentType; response.ContentLength64 = resp.Data.Length; response.OutputStream.Write(resp.Data, 0, resp.Data.Length); response.ContentEncoding = resp.Encoding; } // Whether we do or not, no error occurred, so the response code is OK. // For example, we may have just processed an AJAX callback that does not have a data response. // Use the status code in the response packet, so the controller has an opportunity to set the response. response.StatusCode = (int)resp.StatusCode; } else { response.StatusCode = (int)HttpStatusCode.Redirect; if (String.IsNullOrEmpty(publicIP)) { string redirectUrl = request.Url.Scheme + "://" + request.Url.Host + resp.Redirect; response.Redirect(redirectUrl); } else { // response.Redirect("http://" + publicIP + resp.Redirect); string redirectUrl = request.Url.Scheme + "://" + request.Url.Host + resp.Redirect; response.Redirect(redirectUrl); } } response.OutputStream.Close(); }
// < HELPER METHODS FOR POST PROCESSING STARTS > /// <summary> /// Answers a POST to the request=loginpage resource. /// </summary> /// <param name="response">The HttpListenerResponse obtained from the HttpListenerContext that is associated with the post to the request=loginpage resource.</param> /// <param name="username">The username posted to the resource.</param> private void AnswerLoginpagePost(HttpListenerResponse response, string username) { Contract.Requires(!ReferenceEquals(response, null)); Contract.Requires(!ReferenceEquals(username, null)); // check username is valid in own database if (this.database.ContainsUsername(username)) { Console.WriteLine("[ThirdPartyServer]: Username '" + username + "' successfully found in user-database; redirecting to authenticator."); // redirect to authenticator response.StatusCode = 200; // response.StatusDescription = "Redirecting you to authenticator."; response.Redirect(StringData.AuthUri + "request=redirect&username="******"&3rd=" + this.server.Prefixes.First()); response.Close(); Console.WriteLine("[ThirdPartyServer]: Successfully redirected '" + username + "' to " + StringData.AuthUri + "request=redirect&username="******"&3rd=" + this.server.Prefixes.First()); } else { Console.WriteLine("[ThirdPartyServer]: Username '" + username + "' not found in user-database; aborting request."); response = this.SetupForbiddenResponse(response, "Username not found."); response.Close(); } }
public override void WriteContent(HttpListenerResponse response) { byte[] buf = Encoding.UTF8.GetBytes(_content); response.StatusCode = (int)_statusCode; if (_requestRedirect != null) response.Redirect(_requestRedirect); response.ContentType = "text/html"; response.ContentLength64 = buf.Length; response.OutputStream.Write(buf, 0, buf.Length); }
private bool IsAuthenticating(HttpListenerRequest aRequest, HttpListenerResponse aResponse) { string pathAndQuery = aRequest.Url.PathAndQuery; string location; if (String.Compare(aRequest.HttpMethod, "POST", true) == 0 && pathAndQuery == "/loginService") { MemoryStream memStream = new MemoryStream(); aRequest.InputStream.CopyTo(memStream); byte[] bytes = memStream.ToArray(); XElement tree = XElement.Parse(Encoding.UTF8.GetString(bytes)); string username = tree.Element("username").Value; string password = tree.Element("password").Value; if (!iLoginValidator.ValidateCredentials(username, password)) { aResponse.StatusCode = (int)HttpStatusCode.Unauthorized; aResponse.Close(); return true; } string guid = Guid.NewGuid().ToString(); lock (this) { iAuthenticatedClients.Add(guid, guid); // TODO: write clients to xml file (iff not using session cookies) } aResponse.AppendCookie(new Cookie(kAuthCookieName, guid)); aResponse.StatusCode = (int)HttpStatusCode.OK; location = "/"; byte[] buf = Encoding.UTF8.GetBytes(location + "\r\n"); aResponse.OutputStream.Write(buf, 0, buf.Length); Logger.InfoFormat("Authenticated! Redirecting: {0} to {1}", pathAndQuery, location); // just completed authentication. Redirect client to (assumed) original url aResponse.Close(); return true; } foreach (Cookie cookie in aRequest.Cookies) { if (cookie.Name == kAuthCookieName && iAuthenticatedClients.ContainsKey(cookie.Value)) { // already authenticated. // A path of /{iForwardUdn} is a special case (see docs on our use of HaProxy) which needs to be redirected to "/" if (pathAndQuery == String.Format("/{0}", iForwardUdn)) { aResponse.Redirect("/"); aResponse.Close(); return true; } return false; } } if (pathAndQuery == kLoginPath || pathAndQuery.StartsWith("/login/")) // allow these requests through, regardless of our authentication state as they're needed to load the login screen return false; // redirect any other requests to the login page location = kLoginPath; aResponse.Redirect(location); aResponse.Close(); Logger.InfoFormat("Redirecting: {0} to {1}", pathAndQuery, location); return true; }