/// <summary> /// Initializes a new instance of the <see cref="HttpListenerRequestAdapter" /> class. /// </summary> /// <param name="request">The <see cref="HttpListenerRequest" /> to adapt for WebDAV#.</param> /// <exception cref="System.ArgumentNullException">request</exception> /// <exception cref="ArgumentNullException"><paramref name="request" /> is <c>null</c>.</exception> public HttpListenerRequestAdapter(HttpListenerRequest request) { if (request == null) throw new ArgumentNullException("request"); _request = request; }
public HttpListenerRequestAdapter(HttpListenerRequest request) { this.request = request; this.queryString = System.Web.HttpUtility.ParseQueryString(Uri.UnescapeDataString(request.Url.Query)); Url = this.request.Url; RawUrl = this.request.RawUrl; }
public void HandleGet(HttpListenerRequest request, HttpListenerResponse response) { string queryString = request.Url.Query; var queryParts = Server.ParseQueryString(queryString); string presetName = queryParts.GetFirstValue("preset"); if (string.IsNullOrEmpty(presetName)) { response.StatusCode = 200; response.WriteResponse(presets.GetAll()); } else { string result = presets.Get(presetName); if (result == null) { response.StatusCode = 404; response.WriteResponse("No such preset has been registered"); } else { response.StatusCode = 200; response.WriteResponse(result); } } }
private static string HandleCreateAccount(HttpServer server, HttpListenerRequest request, Dictionary<string, string> parameters) { if (!parameters.ContainsKey("username")) throw new Exception("Missing username."); if (!parameters.ContainsKey("password")) throw new Exception("Missing password."); string username = parameters["username"]; string password = parameters["password"]; if (Databases.AccountTable.Count(a => a.Username.ToLower() == username.ToLower()) > 0) return JsonEncode("Username already in use!"); System.Text.RegularExpressions.Regex invalidCharacterRegex = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]"); if (invalidCharacterRegex.IsMatch(username)) return JsonEncode("Invalid characters detected in username!"); Random getrandom = new Random(); String token = getrandom.Next(10000000, 99999999).ToString(); AccountEntry entry = new AccountEntry(); entry.Index = Databases.AccountTable.GenerateIndex(); entry.Username = username; entry.Password = password; entry.Verifier = ""; entry.Salt = ""; entry.RTW_Points = 0; entry.IsAdmin = 0; entry.IsBanned = 0; entry.InUse = 0; entry.extrn_login = 0; entry.CanHostDistrict = 1; entry.Token = token; Databases.AccountTable.Add(entry); Log.Succes("HTTP", "Successfully created account '" + username + "'"); return JsonEncode("Account created!\n\nYour token is: " + token + ".\nCopy and paste given token in \"_rtoken.id\" file and put it in the same folder where your \"APB.exe\" is located."); }
public override IResponseFormatter Handle(HttpListenerRequest request) { var buildingManager = Singleton<BuildingManager>.instance; if (request.Url.AbsolutePath.StartsWith("/Building/List")) { List<ushort> buildingIDs = new List<ushort>(); var len = buildingManager.m_buildings.m_buffer.Length; for (ushort i = 0; i < len; i++) { if (buildingManager.m_buildings.m_buffer[i].m_flags == Building.Flags.None) { continue; } buildingIDs.Add(i); } return JsonResponse(buildingIDs); } foreach (var building in buildingManager.m_buildings.m_buffer) { if (building.m_flags == Building.Flags.None) { continue; } // TODO: Something with Buildings. } return JsonResponse(""); }
public RestRequest(HttpListenerRequest request) { this.HttpMethod = request.HttpMethod; this.Url = request.Url; this.RESTModuleName = request.Url.Segments[1].Replace("/", ""); this.RESTMethodName = request.Url.Segments[2].Replace("/", ""); this.RESTMethodParameters = request.QueryString; this.Cookies = request.Cookies; if (request.HasEntityBody) { Encoding encoding = request.ContentEncoding; using (var bodyStream = request.InputStream) using (var streamReader = new StreamReader(bodyStream, encoding)) { if (request.ContentType != null) { this.ContentType = request.ContentType; } this.ContentLength = request.ContentLength64; this.Body = streamReader.ReadToEnd(); } if (this.HttpMethod == "POST" && this.ContentType == "application/x-www-form-urlencoded") { this.RESTMethodParameters = ParseQueryString(System.Uri.UnescapeDataString(this.Body)); } } }
public HttpListenerRequestAdapter(HttpListenerRequest request) { this.request = request; Url = this.request.Url; RawUrl = this.request.RawUrl; queryString = HttpRequestHelper.ParseQueryStringWithLegacySupport(request.Headers["Raven-Client-Version"], request.Url.Query); }
/// <summary> /// Creates a new instance of HttpRequest /// </summary> /// <param name="Client">The HttpClient creating this response</param> public HttpRequest(HttpListenerRequest Request, HttpClient Client) { // Create a better QueryString object this.QueryString = Request.QueryString.Cast<string>().ToDictionary(p => p, p => Request.QueryString[p]); this.Request = Request; this.Client = Client; }
private AuthenticationSchemes AuthenticationSchemeSelectorDelegate(HttpListenerRequest request) { var authHeader = request.Headers["Authorization"]; var hasApiKey = "True".Equals(request.Headers["Has-Api-Key"], StringComparison.CurrentCultureIgnoreCase); if(string.IsNullOrEmpty(authHeader) == false && authHeader.StartsWith("Bearer ") || hasApiKey) { // this is an OAuth request that has a token // we allow this to go through and we will authenticate that on the OAuth Request Authorizer return AuthenticationSchemes.Anonymous; } if (NeverSecret.Urls.Contains(request.Url.AbsolutePath)) return AuthenticationSchemes.Anonymous; if (IsAdminRequest.IsMatch(request.RawUrl)) return AuthenticationSchemes.IntegratedWindowsAuthentication; switch (configuration.AnonymousUserAccessMode) { case AnonymousUserAccessMode.All: return AuthenticationSchemes.Anonymous; case AnonymousUserAccessMode.Get: return AbstractRequestAuthorizer.IsGetRequest(request.HttpMethod, request.Url.AbsolutePath) ? AuthenticationSchemes.Anonymous | AuthenticationSchemes.IntegratedWindowsAuthentication : AuthenticationSchemes.IntegratedWindowsAuthentication; case AnonymousUserAccessMode.None: return AuthenticationSchemes.IntegratedWindowsAuthentication; default: throw new ArgumentException(string.Format("Cannot understand access mode: '{0}'", configuration.AnonymousUserAccessMode)); } }
public RouteHandler Find(HttpListenerRequest request, out UriTemplateMatch templateMatch) { var reqId = request.HttpMethod + ":" + request.Url.LocalPath; KeyValuePair<RouteHandler, Uri> rh; if (Cache.TryGetValue(reqId, out rh)) { templateMatch = rh.Key.Template.Match(rh.Value, request.Url); return rh.Key; } templateMatch = null; List<RouteHandler> handlers; if (!MethodRoutes.TryGetValue(request.HttpMethod, out handlers)) return null; var reqUrl = request.Url; var url = reqUrl.ToString(); var baseAddr = new Uri(url.Substring(0, url.Length - request.RawUrl.Length)); foreach (var h in handlers) { var match = h.Template.Match(baseAddr, reqUrl); if (match != null) { templateMatch = match; Cache.TryAdd(reqId, new KeyValuePair<RouteHandler, Uri>(h, baseAddr)); return h; } } return null; }
private void RespondWithNotFound(HttpListenerRequest request, HttpListenerResponse response) { _log.DebugFormat("Responded with 404 Not Found for url {0}", request.Url); response.StatusCode = 404; response.StatusDescription = "Not Found"; response.OutputStream.Close(); }
public HttpEntity(DateTime timeStamp, ICodec requestCodec, ICodec responseCodec, HttpListenerContext context, string[] allowedMethods, Action<HttpEntity> onRequestSatisfied) { Ensure.NotNull(requestCodec, "requestCodec"); Ensure.NotNull(responseCodec, "responseCodec"); Ensure.NotNull(context, "context"); Ensure.NotNull(allowedMethods, "allowedMethods"); Ensure.NotNull(onRequestSatisfied, "onRequestSatisfied"); TimeStamp = timeStamp; UserHostName = context.Request.UserHostName; RequestCodec = requestCodec; ResponseCodec = responseCodec; _context = context; Request = context.Request; Response = context.Response; Manager = new HttpEntityManager(this, allowedMethods, onRequestSatisfied); }
void RequestHandler(HttpListenerRequest req, HttpListenerResponse res) { Console.WriteLine("[RequestHandler: req.url=" + req.Url.ToString()); if (req.Url.AbsolutePath == "/cmd/record/start") { Record.Start(req, res); } else if (req.Url.AbsolutePath == "/cmd/record/stop") { Record.Stop(req, res); } else if (req.Url.AbsolutePath == "/cmd/livingcast/start") { LivingCast.Start(req, res); } else if (req.Url.AbsolutePath == "/cmd/livingcast/stop") { LivingCast.Stop(req, res); } else { res.StatusCode = 404; res.ContentType = "text/plain"; try { StreamWriter sw = new StreamWriter(res.OutputStream); sw.WriteLine("NOT supported command: " + req.Url.AbsolutePath); sw.Close(); } catch { } } }
public override IResponseFormatter Handle(HttpListenerRequest request) { var transportManager = Singleton<TransportManager>.instance; if (transportManager == null) return JsonResponse(new Dictionary<string, List<PublicTransportLine>>()); var lines = transportManager.m_lines.m_buffer.ToList(); if (lines == null) return JsonResponse(new Dictionary<string, List<PublicTransportLine>>()); var busLines = lines.Where(x => x.Info.m_class.m_subService == ItemClass.SubService.PublicTransportBus); var metroLines = lines.Where(x => x.Info.m_class.m_subService == ItemClass.SubService.PublicTransportMetro); var trainLines = lines.Where(x => x.Info.m_class.m_subService == ItemClass.SubService.PublicTransportTrain); var shipLines = lines.Where(x => x.Info.m_class.m_subService == ItemClass.SubService.PublicTransportShip); var planeLines = lines.Where(x => x.Info.m_class.m_subService == ItemClass.SubService.PublicTransportPlane); Dictionary<string, List<PublicTransportLine>> allTransportLines = new Dictionary<string, List<PublicTransportLine>>() { {"BusLines", MakeLinesModels(busLines)}, {"MetroLines", MakeLinesModels(metroLines)}, {"TrainLines", MakeLinesModels(trainLines)}, {"ShipLines", MakeLinesModels(shipLines)}, {"PlaneLines", MakeLinesModels(planeLines)}, }; return JsonResponse(allTransportLines); }
public override void Process(HttpListenerRequest request, HttpListenerResponse response) { using (var stream = typeof(StaticHandler).Assembly.GetManifestResourceStream("SongRequest.Static.favicon.ico")) { stream.CopyTo(response.OutputStream); } }
private static bool PuppetProcessor(HttpListenerRequest request, HttpListenerResponse response) { string content = null; if (request.HttpMethod == "GET") { var contentId = request.QueryString.Count > 0 ? request.QueryString[0] : null; if (string.IsNullOrEmpty(contentId) || !_contentStore.ContainsKey(contentId)) { response.StatusCode = (int)HttpStatusCode.NotFound; return false; } content = _contentStore[contentId]??""; } else { if (request.HasEntityBody) { using (var sr = new StreamReader(request.InputStream)) { content = sr.ReadToEnd(); } } //response.ContentType = "application/json"; } byte[] buf = Encoding.UTF8.GetBytes(content); response.ContentLength64 = buf.Length; response.OutputStream.Write(buf, 0, buf.Length); return true; }
/// <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); }
public BrowserSender(HttpListenerContext context) { Context = context; Request = context.Request; Response = context.Response; User = context.User; }
public override IResponseFormatter Handle(HttpListenerRequest request) { // TODO: Customize request handling. var messages = _chirpRetriever.Messages; return JsonResponse(messages); }
public API(ref HttpListenerContext context, Server myServer) { this.QS = context.Request.QueryString; this.Request = context.Request; this.Response = context.Response; this.Method = new APIMethod(ref this.QS); }
public WebserviceRequest(string url, string rawdata, HttpListenerRequest request) { URL = url; RawData = rawdata; RawRequest = request; ParseData(); }
public HttpListenerRequestWrapper(HttpListenerRequest httpListenerRequest) { _httpListenerRequest = httpListenerRequest; _qs = new NameValueCollection(httpListenerRequest.QueryString); _headers = new NameValueCollection(httpListenerRequest.Headers); _cookies = new CookieCollectionWrapper(_httpListenerRequest.Cookies); }
public string buildResponse(HttpListenerRequest request) { string responseStr = System.IO.File.ReadAllText(_templateFile);//""; string appTableStr = ""; // responseStr = "<HTML><BODY>Hello World!";// + request.Url;// + "</BODY></HTML>"; // responseStr += "<br />Applications:"; // foreach(string s in request.QueryString.AllKeys){ // responseStr += "<br />" + s + " " + request.QueryString[s]; // } appTableStr += "<table>"; foreach(Application app in appList){ //appTableStr += "<br /><a href=\"http://localhost:8080/?LAUNCH=" + app.name + "\">"; appTableStr += "<tr><td>"; if (app.icon != null){ System.Drawing.Bitmap bmp = app.icon.ToBitmap(); System.IO.MemoryStream stream = new System.IO.MemoryStream(); bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png); byte[] imageBytes = stream.ToArray(); appTableStr += "<a href=\"http://localhost:8080/?LAUNCH=" + app.name + "\"><img src=\"data:image/png;base64," + Convert.ToBase64String(imageBytes) + "\" /></a>"; } appTableStr += "</td><td><a href=\"http://localhost:8080/?LAUNCH=" + app.name + "\">" + app.name + "</a></tr>"; } appTableStr += "</table>"; //responseStr += appTableStr + "</BODY></HTML>"; responseStr = responseStr.Replace("[!AppTable!]",appTableStr); return responseStr; }
public HttpListenerWebConnection(IWebServer webServer, HttpListenerContext context) : base(webServer, CallingFrom.Web) { Context = context; Request = Context.Request; Response = Context.Response; }
public override string Execute(HttpListenerRequest request) { //we need to do match making here var dat = GetUrlGets(request.RawUrl); return "Wait"; }
public HttpRequest(HttpListenerRequest listenerRequest) { _request = listenerRequest; _formData = new FormData(listenerRequest); LoadFormData(); }
/// <summary> /// 处理程序 /// </summary> /// <param name="request">请求上下文</param> public string Handle(HttpListenerRequest requestContext) { var command = requestContext.QueryString["command"]; //byte[] fileBuffer = new byte[1024 * 32]; //using (MemoryStream ms = new MemoryStream()) //{ // while (true) // { // int read = requestContext.InputStream.Read(fileBuffer, 0, fileBuffer.Length); // if (read <= 0) // { // FileStream fs = new FileStream("C:\\111.xlsx", FileMode.OpenOrCreate); // byte[] buff = ms.ToArray(); // fs.Write(buff, 0, buff.Length); // fs.Close(); // break; // } // ms.Write(fileBuffer, 0, read); // } //} return "200"; }
internal ListenerRequest(HttpListenerRequest innerRequest, IContext context) { if (innerRequest == null) throw new ArgumentNullException("innerRequest"); if (context == null) throw new ArgumentNullException("context"); InnerRequest = innerRequest; _context = context; }
static void GetFileHandler(HttpListenerRequest request, HttpListenerResponse response) { var query = request.QueryString; string targetLocation = query["target"]; Log ("GetFile: " + targetLocation + "..."); if(File.Exists(targetLocation)) { try { using(var inStream = File.OpenRead(targetLocation)) { response.StatusCode = 200; response.ContentType = "application/octet-stream"; CopyStream(inStream, response.OutputStream); } } catch(Exception e) { Log (e.Message); response.StatusCode = 501; } } else { response.StatusCode = 501; Log ("File doesn't exist"); } }
public void Process(HttpListenerRequest request, HttpListenerResponse response) { try { if (request.HttpMethod != "GET") { response.StatusCode = 405; response.StatusDescription = "Method Not Supported"; response.Close(); return; } string version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion; string status = GetStatusDescription(); string timestamp = DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "Z"; FormatJsonResponse(response, version, status, timestamp); } catch (HttpListenerException hlex) { Supervisor.LogException(hlex, TraceEventType.Error, request.RawUrl); response.StatusCode = 500; response.StatusDescription = "Error Occurred"; response.Close(); } }
FormFile[] ParseMultipart(System.Net.HttpListenerRequest rq) { /* Typical multipart body would be: * ------WebKitFormBoundaryVXXOTFUWdfGpOcFK * Content-Disposition: form-data; name="f1"; filename="test.txt" * Content-Type: text/plain * * Hello there * * ------WebKitFormBoundaryVXXOTFUWdfGpOcFK * Content-Disposition: form-data; name="submit" * * Upload * ------WebKitFormBoundaryVXXOTFUWdfGpOcFK-- */ var flist = new G.List <FormFile>(); byte[] data = ToByteArray(rq.InputStream); System.Text.Encoding encoding = System.Text.Encoding.UTF8; // Not entirely clear what encoding should be used for headers. int pos = 0; /* Index into data */ while (true) { int headerLength = IndexOf(data, encoding.GetBytes("\r\n\r\n"), pos) - pos + 4; if (headerLength < 4) { break; } string headers = encoding.GetString(data, pos, headerLength); pos += headerLength; // The first header line is the delimiter string delimiter = headers.Substring(0, headers.IndexOf("\r\n")); // Extract atrtributes from header string contentType = Look(@"(?<=Content\-Type:)(.*?)(?=\r\n)", headers); string name = Look(@"(?<= name\=\"")(.*?)(?=\"")", headers); string filename = Look(@"(?<=filename\=\"")(.*?)(?=\"")", headers); // Get the content length byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter); int contentLength = IndexOf(data, delimiterBytes, pos) - pos; if (contentLength < 0) { break; } // Extract the content from data byte[] content = new byte[contentLength]; System.Buffer.BlockCopy(data, pos, content, 0, contentLength); pos += contentLength + delimiterBytes.Length; flist.Add(new FormFile(name, contentType, filename, content)); } return(flist.ToArray()); }
/// <summary> /// Initializes a new instance of the <see cref="SystemHttpRequest"/> class. /// </summary> /// <param name="context">The context.</param> public SystemHttpRequest(System.Net.HttpListenerContext context) { _request = context.Request; Enum.TryParse <HttpVerbs>(_request.HttpMethod.Trim(), true, out var verb); HttpVerb = verb; Cookies = new SystemCookieCollection(_request.Cookies); LocalEndPoint = _request.LocalEndPoint; RemoteEndPoint = _request.RemoteEndPoint; }
/// <summary> /// Called whenever something goes wrong in either the BeginAuthentication /// TryEndAuthentication methods. Calls AdapterPresentation to display /// a nice message to the end user. /// </summary> /// <param name="request"></param> /// <param name="ex"></param> /// <returns></returns> public IAdapterPresentation OnError(System.Net.HttpListenerRequest request, ExternalAuthenticationException ex) { Logging.LogMessage( "An error occured authenticating a user." + Environment.NewLine + Environment.NewLine + "Username: "******"Error: " + ex.Message); return(new AdapterPresentation(ex.Message, true)); }
public override Task <string> GetResponseString(string method, System.Net.HttpListenerRequest request, NameValueCollection queryString, string data) { if (method == "GET") { return(base.GetResponseString(method, request, queryString, data)); } else if (method == "POST") { return(GetPostedResponseString(request, queryString, data)); } return(null); }
public async Task <string> GetPostedResponseString(System.Net.HttpListenerRequest request, NameValueCollection queryString, string data) { var dict = await data.ToObjectAsync <Dictionary <string, string> > (); var deviceId = queryString ["deviceId"]; var command = dict ["command"]; var nodeDevice = await NodeDatabase.Shared.GetDevice(deviceId); nodeDevice.PerferedCommand = command; await NodeDatabase.Shared.InsertDevice(nodeDevice); return(new { Success = true }.ToJson()); }
public override object HandleGET(System.Net.HttpListenerRequest request, ref UtilityClasses.HTTPResponse response) { try { response = ObjectsFactories.HTTPResponseFactory.GetObject().CreateCodeOK(); return(tagsDAO.GetAllTags()); } catch (Exception e) { response = ObjectsFactories.HTTPResponseFactory.GetObject().CreateCodeInternalServerError(); return(response); } }
public override object HandlePOST(System.Net.HttpListenerRequest request, ref UtilityClasses.HTTPResponse response) { try { string json = GetRequestData(request); response = ObjectsFactories.HTTPResponseFactory.GetObject().CreateCodeCreated(); return(usersDAO.SaveUsers(json)); } catch (Exception e) { response = ObjectsFactories.HTTPResponseFactory.GetObject().CreateCodeInternalServerError(); return(response); } }
public override object HandlePOST(System.Net.HttpListenerRequest request, ref UtilityClasses.HTTPResponse response) { try { string json = GetRequestData(request); Poll poll = JsonConvert.DeserializeObject <Poll>(json); response = ObjectsFactories.HTTPResponseFactory.GetObject().CreateCodeCreated(); return(UserFilledAnswersSaver.GetObject().SaveFilledPoll(poll)); } catch (Exception e) { response = ObjectsFactories.HTTPResponseFactory.GetObject().CreateCodeInternalServerError(); return(response); } }
public SystemHttpRequest(System.Net.HttpListenerRequest request) { _request = request; if (!String.IsNullOrEmpty(ContentType) && ContentType.Contains("multipart/form-data")) { multipartFormDataParser = MultipartFormDataParser.Parse(InputStream); _form = multipartFormDataParser.Parameters; _files = multipartFormDataParser.Files; } else { _form = new List <ParameterPart>(); _files = new List <FilePart>(); } }
static void httpListenerCallback(IAsyncResult result) { System.Net.HttpListener listener = (System.Net.HttpListener)result.AsyncState; try { if (listener.IsListening) { // continue to listen listener.BeginGetContext(new AsyncCallback(httpListenerCallback), listener); // handle the incoming request System.Net.HttpListenerContext context = listener.EndGetContext(result); System.Net.HttpListenerRequest request = context.Request; string responseString; if (string.Compare("/appletv/us/js/application.js", request.Url.LocalPath, true) == 0) { responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\application.js"); } else if (string.Compare("/appletv/us/nav.xml", request.Url.LocalPath, true) == 0) { responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\index.xml"); } else if (string.Compare("/appletv/studios/marvel/ironman3/index-hd.xml", request.Url.LocalPath, true) == 0) { responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\ironman3.index-hd.xml"); } else if (string.Compare("/appletv/studios/marvel/ironman3/videos/trailer1-hd.xml", request.Url.LocalPath, true) == 0) { responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\com.apple.trailers\ironman3.videos.trailer1-hd.xml"); } else { responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\atv\index.xml"); } System.Net.HttpListenerResponse response = context.Response; //string responseString = System.IO.File.ReadAllText(@"D:\projects\local\atv\atv\index.xml"); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } } catch (Exception ex) { } }
private void WxHttpServer_OnDataReceived(System.Net.HttpListenerRequest reqeust, System.Net.HttpListenerResponse response) { String dataString = ""; if (reqeust.HttpMethod == "POST") { Console.WriteLine("POST"); Stream stream = reqeust.InputStream; BinaryReader binaryReader = new BinaryReader(stream); byte[] data = new byte[reqeust.ContentLength64]; binaryReader.Read(data, 0, (int)reqeust.ContentLength64); dataString = Encoding.UTF8.GetString(data); lock (locker) { foreach (String keyWords in keyWordList) { if (dataString == "") { return; } if (dataString.IndexOf(keyWords) > -1) { DeleteUser(dataString, keyWords); break; } } } } string responseString = ""; byte[] buffer = Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); }
private void WxHttpServer_OnDataReceived(System.Net.HttpListenerRequest reqeust, System.Net.HttpListenerResponse response) { String dataString = ""; string responseString = ""; if (reqeust.HttpMethod == "POST") { Console.WriteLine("POST"); Stream stream = reqeust.InputStream; BinaryReader binaryReader = new BinaryReader(stream); byte[] data = new byte[reqeust.ContentLength64]; binaryReader.Read(data, 0, (int)reqeust.ContentLength64); dataString = Encoding.UTF8.GetString(data); JavaScriptSerializer js = new JavaScriptSerializer(); ClientCmd clientCmd = js.Deserialize <ClientCmd>(dataString); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(clientCmd.Wxid); Boolean result = DeleteWxUser(stringBuilder); responseString = ( new { cmd = clientCmd.Cmd, result = result.ToString() } ).ToString(); } byte[] buffer = Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); }
public override object HandleGET(System.Net.HttpListenerRequest request, ref UtilityClasses.HTTPResponse response) { ObjectsFactories.PollsFactory factory = new ObjectsFactories.PollsFactory(); RESTCollectionElementID collectionElementID = GetCollectionElementID(request); try { if (collectionElementID.IsCollection()) { response = ObjectsFactories.HTTPResponseFactory.GetObject().CreateCodeOK(); return(factory.CreateFilledPolls().WithTags().GetPolls()); } else { response = ObjectsFactories.HTTPResponseFactory.GetObject().CreateCodeOK(); return(factory.CreateFilledPoll(collectionElementID.elementNumber).WithAllFilled().GetPoll()); } } catch (Exception e) { response = ObjectsFactories.HTTPResponseFactory.GetObject().CreateCodeInternalServerError(); return(response); } }
public IAdapterPresentation BeginAuthentication(System.Security.Claims.Claim identityClaim, System.Net.HttpListenerRequest request, IAuthenticationContext context) { string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows); System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap(); fileMap.ExeConfigFilename = windir + "\\ADFS\\OktaMFA-ADFS.dll.config"; System.Configuration.Configuration cfg = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None); string oktaTenant = cfg.AppSettings.Settings["Tenant"].Value; string authToken = cfg.AppSettings.Settings["apiKey"].Value; string upn = identityClaim.Value; string baseUrl = oktaTenant + "/api/v1/"; //string tenantName = "marcjordan"; //string baseUrl = "https://" + tenantName + ".oktapreview.com/api/v1/"; //string authToken = "SSWS 009RUU8EeUvD-EpOEH1qHL0OZwmCTJK71kzFjsQufr"; string pinSuccess = "no"; string verifyResult = "false"; string userID = ""; bool isPermanentFailure = false; string message = string.Empty; int messageVal; messageVal = 2; HttpWebRequest upnRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + upn); upnRequest.Headers.Add("Authorization", authToken); upnRequest.Method = "GET"; upnRequest.ContentType = "application/json"; try { var upnResponse = (HttpWebResponse)upnRequest.GetResponse(); var idReader = new StreamReader(upnResponse.GetResponseStream()); var id = idReader.ReadToEnd(); RootObject userProfile = JsonConvert.DeserializeObject <RootObject>(id); userID = userProfile.id.ToString(); HttpWebRequest factorRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors"); factorRequest.Headers.Add("Authorization", authToken); factorRequest.Method = "GET"; factorRequest.ContentType = "application/json"; factorRequest.Accept = "application/json"; var factorResponse = (HttpWebResponse)factorRequest.GetResponse(); var factorReader = new StreamReader(factorResponse.GetResponseStream()); var factorList = factorReader.ReadToEnd(); RootObject[] factors = JsonConvert.DeserializeObject <RootObject[]>(factorList); foreach (RootObject factor in factors) { if (factor.factorType == "sms") { string smsfactorID = factor.id; HttpWebRequest smsRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + smsfactorID + "/verify"); smsRequest.Headers.Add("Authorization", authToken); smsRequest.Method = "POST"; smsRequest.ContentType = "application/json"; smsRequest.Accept = "application/json"; var smsResponse = (HttpWebResponse)smsRequest.GetResponse(); messageVal = 1; } } } catch (System.Net.WebException e) { messageVal = 2; } return(new AdapterPresentation(message, upn, isPermanentFailure, userID, messageVal, oktaTenant)); }
public IAdapterPresentation TryEndAuthentication(IAuthenticationContext context, IProofData proofData, System.Net.HttpListenerRequest request, out System.Security.Claims.Claim[] claims) { claims = null; IAdapterPresentation result = null; string userName = proofData.Properties["upn"].ToString(); string userID = proofData.Properties["userID"].ToString(); string pin = proofData.Properties["pin"].ToString(); string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows); System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap(); fileMap.ExeConfigFilename = windir + "\\ADFS\\OktaMFA-ADFS.dll.config"; System.Configuration.Configuration cfg = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None); string oktaTenant = cfg.AppSettings.Settings["Tenant"].Value; string authToken = cfg.AppSettings.Settings["apiKey"].Value; string baseUrl = oktaTenant + "/api/v1/"; string pinSuccess = "no"; string verifyResult = "false"; HttpWebRequest factorRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors"); factorRequest.Headers.Add("Authorization", authToken); factorRequest.Method = "GET"; factorRequest.ContentType = "application/json"; factorRequest.Accept = "application/json"; var factorResponse = (HttpWebResponse)factorRequest.GetResponse(); var factorReader = new StreamReader(factorResponse.GetResponseStream()); var factorList = factorReader.ReadToEnd(); RootObject[] factors = JsonConvert.DeserializeObject <RootObject[]>(factorList); string factorID = ""; foreach (RootObject factor in factors) { if (factor.factorType == "sms") { factorID = factor.id; HttpWebRequest verifyRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + factorID + "/verify"); verifyRequest.Headers.Add("Authorization", authToken); verifyRequest.Method = "POST"; verifyRequest.ContentType = "application/json"; otpCode otpCode = new otpCode { passCode = pin }; string otpString = JsonConvert.SerializeObject(otpCode); using (var streamWriter = new StreamWriter(verifyRequest.GetRequestStream())) { streamWriter.Write(otpString); } try { var verifyResponse = (HttpWebResponse)verifyRequest.GetResponse(); if (verifyResponse.StatusCode.ToString() == "OK" && pin != "") { pinSuccess = "yes"; Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); claims = new Claim[] { claim }; return(result); } } catch (WebException we) { var failResponse = we.Response as HttpWebResponse; if (failResponse == null) { throw; } result = new AdapterPresentation("Authentication was unsuccessful, did you enter the sms code correctly?", proofData.Properties["upn"].ToString(), false, proofData.Properties["userID"].ToString()); } } } if (pinSuccess == "yes") { Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); claims = new Claim[] { claim }; return(result); } else { result = new AdapterPresentation("Authentication was unsuccessful, did you enter the sms code correctly?", proofData.Properties["upn"].ToString(), false, proofData.Properties["userID"].ToString()); } return(result); }
public IAdapterPresentation OnError(System.Net.HttpListenerRequest request, ExternalAuthenticationException ex) { return(new AdapterPresentation(ex.Message, true)); }
private void processRequest() { // Set WWW Root Path string rootPath = Directory.GetCurrentDirectory() + "\\WWWRoot\\"; // Set default page string defaultPage = "index.html"; try { // 以Request屬性取得HTTP伺服端的輸入串流,則用戶端之請求 httpRequest = httpContext.Request; // // 顯示HttpListenerRequest類別的屬性取得HTTP請求之相關內容 // // 用戶端所能接受的MIME類型 string[] types = httpRequest.AcceptTypes; if (types != null) { Console.WriteLine("用戶端所能接受的MIME類型:"); foreach (string type in types) { Console.WriteLine(" {0}", type); } } // Content Length Console.WriteLine("Content Length {0}", httpRequest.ContentLength64); // Content Type if (httpRequest.ContentType != null) { Console.WriteLine("Content Type {0}", httpRequest.ContentType); } // Cookie foreach (Cookie cookie in httpRequest.Cookies) { Console.WriteLine("Cookie:"); Console.WriteLine(" {0} = {1}", cookie.Name, cookie.Value); Console.WriteLine(" 網域屬性: {0}", cookie.Domain); Console.WriteLine(" 有效期限: {0} (expired? {1})", cookie.Expires, cookie.Expired); Console.WriteLine(" URI路徑屬性: {0}", cookie.Path); Console.WriteLine(" 通訊埠: {0}", cookie.Port); Console.WriteLine(" 安全層級: {0}", cookie.Secure); Console.WriteLine(" 發出的時間: {0}", cookie.TimeStamp); Console.WriteLine(" 版本: RFC {0}", cookie.Version == 1 ? "2109" : "2965"); Console.WriteLine(" 內容: {0}", cookie.ToString()); } // 用戶端所傳送資料內容的標題資訊 System.Collections.Specialized.NameValueCollection headers = httpRequest.Headers; foreach (string key in headers.AllKeys) { string[] values = headers.GetValues(key); if (values.Length > 0) { Console.WriteLine("用戶端所傳送資料內容的標題資訊:"); foreach (string value in values) { Console.WriteLine(" {0}", value); } } } Console.WriteLine("HTTP通訊協定方法: {0}", httpRequest.HttpMethod); Console.WriteLine("HTTP請求是否自本機送出? {0}", httpRequest.IsLocal); Console.WriteLine("是否保持持續性連結: {0}", httpRequest.KeepAlive); Console.WriteLine("Local End Point: {0}", httpRequest.LocalEndPoint.ToString()); Console.WriteLine("Remote End Point: {0}", httpRequest.RemoteEndPoint.ToString()); Console.WriteLine("HTTP通訊協定的版本: {0}", httpRequest.ProtocolVersion); Console.WriteLine("URL: {0}", httpRequest.Url.OriginalString); Console.WriteLine("Raw URL: {0}", httpRequest.RawUrl); Console.WriteLine("Query: {0}", httpRequest.QueryString); Console.WriteLine("Referred by: {0}", httpRequest.UrlReferrer); // // End of 顯示HttpListenerRequest類別的屬性取得HTTP請求之相關內容 // // 取得相對URL string url = httpRequest.RawUrl; if (url.StartsWith("/")) { url = url.Substring(1); } if (url.EndsWith("/") || url.Equals("")) { url = url + defaultPage; } string request = rootPath + url; sendHTMLResponse(request); } catch (Exception ex) { Console.WriteLine("Exception: " + ex.StackTrace.ToString()); } }
/// <summary> /// Called by AD FS to perform the actual authentication. /// </summary> /// <param name="context"></param> /// <param name="proofData"></param> /// <param name="request"></param> /// <param name="claims"></param> /// <returns> If the Authentication Adapter has successfully performed /// the authentication a claim of type /// http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod /// is returned /// </returns> public IAdapterPresentation TryEndAuthentication(IAuthenticationContext context, IProofData proofData, System.Net.HttpListenerRequest request, out System.Security.Claims.Claim[] claims) { claims = null; IAdapterPresentation result = null; // Ensure the submitted form isn't empty. if (proofData == null || proofData.Properties == null || !proofData.Properties.ContainsKey("pin")) { if (this.debugLogging) { Logging.LogMessage("Either proofData is null or does not contain required property"); } throw new ExternalAuthenticationException(resMgr.GetString("Error_InvalidPIN", new System.Globalization.CultureInfo(context.Lcid)), context); } string pin = proofData.Properties["pin"].ToString(); string userName = this.identityClaim.Split('\\')[1]; // Construct RADIUS auth request. var authPacket = radiusClient.Authenticate(userName, pin); byte[] bIP = IPAddress.Parse(appConfig.NasAddress).GetAddressBytes(); authPacket.SetAttribute(new RadiusAttribute(RadiusAttributeType.NAS_IP_ADDRESS, bIP)); var receivedPacket = radiusClient.SendAndReceivePacket(authPacket).Result; // Handle no response from RADIUS server. if (receivedPacket == null) { if (this.debugLogging) { Logging.LogMessage("No response received from RADIUS server."); } throw new ExternalAuthenticationException(resMgr.GetString("Error_RADIUS_NULL", new System.Globalization.CultureInfo(context.Lcid)), context); } // Examine the different RADIUS responses switch (receivedPacket.PacketType) { case RadiusCode.ACCESS_ACCEPT: System.Security.Claims.Claim claim = new System.Security.Claims.Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); claims = new System.Security.Claims.Claim[] { claim }; break; case RadiusCode.ACCESS_CHALLENGE: // No way to cater for this. Fail. result = new AdapterPresentation(resMgr.GetString("Error_RADIUS_ACCESS_CHALLENGE", new System.Globalization.CultureInfo(context.Lcid)), false); break; case RadiusCode.ACCESS_REJECT: result = new AdapterPresentation(resMgr.GetString("Error_InvalidPIN", new System.Globalization.CultureInfo(context.Lcid)), false); break; default: result = new AdapterPresentation(resMgr.GetString("Error_RADIUS_OTHER", new System.Globalization.CultureInfo(context.Lcid)), false); break; } if (this.debugLogging) { Logging.LogMessage( "Processed authentication response." + Environment.NewLine + "Packet Type: " + receivedPacket.PacketType.ToString() + Environment.NewLine + "User: " + this.identityClaim); } return(result); }
public IAdapterPresentation TryEndAuthentication(IAuthenticationContext context, IProofData proofData, System.Net.HttpListenerRequest request, out System.Security.Claims.Claim[] claims) { claims = null; IAdapterPresentation result = null; string userName = proofData.Properties["upn"].ToString(); string pin = proofData.Properties["pin"].ToString(); string pollingEndpoint = proofData.Properties["pollingEndpoint"].ToString(); string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows); System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap(); fileMap.ExeConfigFilename = windir + "\\ADFS\\OktaMFA-ADFS.dll.config"; System.Configuration.Configuration cfg = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None); string oktaTenant = cfg.AppSettings.Settings["Tenant"].Value; string authToken = cfg.AppSettings.Settings["apiKey"].Value; string baseUrl = oktaTenant + "/api/v1/"; string pinSuccess = "no"; string verifyResult = "false"; HttpWebRequest upnRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userName); upnRequest.Headers.Add("Authorization", authToken); upnRequest.Method = "GET"; upnRequest.ContentType = "application/json"; var upnResponse = (HttpWebResponse)upnRequest.GetResponse(); var idReader = new StreamReader(upnResponse.GetResponseStream()); var id = idReader.ReadToEnd(); RootObject userProfile = JsonConvert.DeserializeObject <RootObject>(id); string userID = userProfile.id.ToString(); HttpWebRequest factorRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors"); factorRequest.Headers.Add("Authorization", authToken); factorRequest.Method = "GET"; factorRequest.ContentType = "application/json"; factorRequest.Accept = "application/json"; var factorResponse = (HttpWebResponse)factorRequest.GetResponse(); var factorReader = new StreamReader(factorResponse.GetResponseStream()); var factorList = factorReader.ReadToEnd(); RootObject[] factors = JsonConvert.DeserializeObject <RootObject[]>(factorList); string factorID = ""; foreach (RootObject factor in factors) { if (factor.provider == "OKTA" && factor.factorType == "push") { // string pushfactorID = factor.id; // HttpWebRequest pushRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + pushfactorID + "/verify"); // pushRequest.Headers.Add("Authorization", authToken); // pushRequest.Method = "POST"; // pushRequest.ContentType = "application/json"; // pushRequest.Accept = "application/json"; // pushRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"; // var pushResponse = (HttpWebResponse)pushRequest.GetResponse(); // var pushReader = new StreamReader(pushResponse.GetResponseStream()); // var pushStatus = pushReader.ReadToEnd(); // RootObject pushResult = JsonConvert.DeserializeObject<RootObject>(pushStatus); // string pollingEndpoint = pushResult._links.poll.href.ToString(); int attemptPoll = 1; while (verifyResult == "false" && attemptPoll <= 20 && pinSuccess == "no") { HttpWebRequest verifyRequest = (HttpWebRequest)WebRequest.Create(pollingEndpoint); verifyRequest.Headers.Add("Authorization", authToken); verifyRequest.Method = "GET"; verifyRequest.ContentType = "application/json"; verifyRequest.Accept = "application/json"; verifyRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"; var pushAnswer = (HttpWebResponse)verifyRequest.GetResponse(); var pushStatus2 = new StreamReader(pushAnswer.GetResponseStream()); var pushStatus3 = pushStatus2.ReadToEnd(); RootObject pushWait = JsonConvert.DeserializeObject <RootObject>(pushStatus3); if (pushWait.factorResult == "SUCCESS") { verifyResult = "true"; Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); claims = new Claim[] { claim }; return(result); } else { attemptPoll++; } } return(result); } if (factor.provider == "OKTA" && factor.factorType == "token:software:totp" && verifyResult == "false" && pin != "") { factorID = factor.id; HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + factorID + "/verify"); httprequest.Headers.Add("Authorization", authToken); httprequest.Method = "POST"; httprequest.ContentType = "application/json"; otpCode otpCode = new otpCode { passCode = pin }; string otpString = JsonConvert.SerializeObject(otpCode); using (var streamWriter = new StreamWriter(httprequest.GetRequestStream())) { streamWriter.Write(otpString); } try { var httpResponse = (HttpWebResponse)httprequest.GetResponse(); if (httpResponse.StatusCode.ToString() == "OK" && pin != "") { pinSuccess = "yes"; Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); claims = new Claim[] { claim }; return(result); } // using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) // { // var factorResult = streamReader.ReadToEnd(); // } } catch (WebException we) { var failResponse = we.Response as HttpWebResponse; if (failResponse == null) { throw; } result = new AdapterPresentation("Authentication failed.", proofData.Properties["upn"].ToString(), false); } } } //HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + factorID + "/verify"); //httprequest.Headers.Add("Authorization", authToken); //httprequest.Method = "POST"; //httprequest.ContentType = "application/json"; //otpCode otpCode = new otpCode //{ passCode = pin }; //string otpString = JsonConvert.SerializeObject(otpCode); //using (var streamWriter = new StreamWriter(httprequest.GetRequestStream())) //{ // streamWriter.Write(otpString); //} //try //{ // var httpResponse = (HttpWebResponse)httprequest.GetResponse(); // if (httpResponse.StatusCode.ToString() == "OK") // { // System.Security.Claims.Claim claim = new System.Security.Claims.Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); // claims = new System.Security.Claims.Claim[] { claim }; // } // using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) // { // var factorResult = streamReader.ReadToEnd(); // } //} //catch (WebException we) //{ // var failResponse = we.Response as HttpWebResponse; // if (failResponse == null) // throw; // result = new AdapterPresentation("Authentication failed.", proofData.Properties["upn"].ToString(), false); //} if (pinSuccess == "yes" || verifyResult == "true") { Claim claim = new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod", "http://schemas.microsoft.com/ws/2012/12/authmethod/otp"); claims = new Claim[] { claim }; return(result); } else { result = new AdapterPresentation("Authentication failed.", proofData.Properties["upn"].ToString(), false); } return(result); }
// Authentication should perform the actual authentication and return at least one Claim on success. // proofData contains a dictionnary of strings to objects that have been asked in the BeginAuthentication public IAdapterPresentation TryEndAuthentication(IAuthenticationContext ctx, IProofData proofData, System.Net.HttpListenerRequest request, out Claim[] claims) { string formAction, upn, msspTransId, logInfo; int state; if (proofData.Properties.ContainsKey("Retry")) { formAction = "Retry"; } else { try { formAction = (string)proofData.Properties["Action"]; } catch (KeyNotFoundException) { formAction = null; } }; //if (formAction == null && proofData.Properties.ContainsKey("SignOut")) { // // if user modifies URL manually during a session, the Cancel action is not captured by ADFS but leaks to this method // formAction = "SignOut"; //}; logger.TraceEvent(TraceEventType.Verbose, 0, "TryEndAuthentication(act:" + formAction + ", ctx:" + _str(ctx) + ", prf:" + _str(proofData) + ", req:" + _str(request)); Logging.Log.TryEndAuthenticationStart(formAction, _str(ctx), _str(proofData), _str(request)); CultureInfo culture = new CultureInfo(ctx.Lcid); upn = (string)ctx.Data[USERUPN]; state = (int)ctx.Data[STATE]; try { // msspTransId is expected to be absent in some error cases, e.g. error 107 msspTransId = (string)ctx.Data[MSSPTRXID]; } catch (KeyNotFoundException) { msspTransId = null; }; logInfo = "upn:\"" + upn + "\", msspTransId:\"" + msspTransId + "\""; claims = null; if (formAction == "Continue") { switch (state) { case 3: logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_OK: " + logInfo + ", state:" + state); Logging.Log.AuthenticationSuccess(state, (int)ctx.Data[STATE], upn, msspTransId); claims = ClaimsHwToken; return(null); case 1: case 31: // fall through for looping below break; default: logger.TraceEvent(TraceEventType.Error, 0, "BAD_STATE: " + logInfo + ", state:" + state); Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, "BAD_STATE"); return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, "action:\"Conitnue\"; state:" + state)); } // check session age, i.e. timespan(Now, authBegin) int ageSeconds = (int)((DateTime.UtcNow.Ticks / 10000 - (long)ctx.Data[AUTHBEGIN]) / 1000); if (ageSeconds >= cfgMid.RequestTimeOutSeconds) { ctx.Data[STATE] = 13; logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_TIMEOUT_CONT: " + logInfo + ", state:" + ctx.Data[STATE] + ", age:" + ageSeconds); Logging.Log.AuthenticationTimeout(state, (int)ctx.Data[STATE], ageSeconds, upn, msspTransId); return (((int)ctx.Data[SESSTRIES] < cfgAdfs.SessionMaxTries) ? new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, "Timeout.") : // TODO: construct new ErrorCode for easier I18N new AdapterPresentation(AuthView.AuthError, cfgAdfs, "Timeout.")); } AuthRequestDto req = new AuthRequestDto(); req.PhoneNumber = (string)ctx.Data[MSISDN]; req.DataToBeSigned = (string)ctx.Data[DTBS]; bool needCheckUserSerialNumber = !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowAbsence) || !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowMismatch) || cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.warnMismatch); if (needCheckUserSerialNumber /* cfgMid.UserSerialNumberPolicy != UserSerialNumberPolicy.ignore */ && ctx.Data.ContainsKey(UKEYSN)) { req.UserSerialNumber = (string)ctx.Data[UKEYSN]; } AuthResponseDto rsp; for (int i = ageSeconds; i <= cfgMid.RequestTimeOutSeconds; i += cfgMid.PollResponseIntervalSeconds) { rsp = getWebClient().PollSignature(req, msspTransId); switch (rsp.Status.Code) { case ServiceStatusCode.SIGNATURE: case ServiceStatusCode.VALID_SIGNATURE: ctx.Data[STATE] = 10; logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_OK: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i); Logging.Log.AuthenticationSuccess(state, (int)ctx.Data[STATE], upn, msspTransId); // EventLog.WriteEntry(EVENTLOGSource, "Authentication success for " + upn, EventLogEntryType.SuccessAudit, 100); claims = ClaimsHwToken; return(null); case ServiceStatusCode.OUSTANDING_TRANSACTION: ctx.Data[STATE] = 11; logger.TraceEvent(TraceEventType.Verbose, 0, "AUTHN_PENDING: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i); Logging.Log.AuthenticationPending(state, (int)ctx.Data[STATE], upn, msspTransId); System.Threading.Thread.Sleep(1000); break; case ServiceStatusCode.EXPIRED_TRANSACTION: ctx.Data[STATE] = 13; logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_TIMEOUT_MID: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i); Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code)); return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp)); case ServiceStatusCode.PB_SIGNATURE_PROCESS: ctx.Data[STATE] = 13; logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_SIGN_PROCESS: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i); Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code)); return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp)); case ServiceStatusCode.USER_CANCEL: ctx.Data[STATE] = 14; logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_CANCEL: " + logInfo + ", state:" + ctx.Data[STATE] + ", i:" + i); Logging.Log.AuthenticationCancel(state, (int)ctx.Data[STATE], upn, msspTransId); return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp)); default: ctx.Data[STATE] = 12; logger.TraceEvent(TraceEventType.Error, 0, "TECH_ERROR: " + logInfo + ", state:" + ctx.Data[STATE] + ", srvStatusCode:" + (int)rsp.Status.Code + ", srvStatusMsg:\"" + rsp.Status.Message + "\", srvStatusDetail:\"" + (string)rsp.Detail + "\""); if (rsp.Status.Color == ServiceStatusColor.Yellow || rsp.Status.Color == ServiceStatusColor.Green) { Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code)); } else { Logging.Log.AuthenticationTechnicalError(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code), (string)rsp.Detail); }; return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, rsp)); } } ; // for-loop ctx.Data[STATE] = 13; logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_TIMEOUT_ADFS: " + logInfo + ", state:" + ctx.Data[STATE]); Logging.Log.AuthenticationTimeout(state, (int)ctx.Data[STATE], cfgMid.RequestTimeOutSeconds, upn, msspTransId); return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, "Timeout.")); } else if (formAction == "Retry") { switch (state) { case 13: case 5: case 35: case 4: case 14: case 34: { // check session age and number of retries int ageSeconds = (int)((DateTime.UtcNow.Ticks / 10000 - (long)ctx.Data[SESSBEGIN]) / 1000); if (ageSeconds >= cfgAdfs.SessionTimeoutSeconds) { logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_SESSION_TIMEOUT: " + logInfo + ", state:" + ctx.Data[STATE] + ", age:" + ageSeconds); Logging.Log.SessionTimeout(state, (int)ctx.Data[STATE], ageSeconds, upn, msspTransId); ctx.Data[STATE] = 22; } else if ((int)ctx.Data[SESSTRIES] >= cfgAdfs.SessionMaxTries) { logger.TraceEvent(TraceEventType.Information, 0, "AUTHN_SESSION_OVERTRIES: " + logInfo + ", state:" + ctx.Data[STATE]); Logging.Log.SessionTooMuchRetries(state, (int)ctx.Data[STATE], (int)ctx.Data[SESSTRIES], upn, msspTransId); ctx.Data[STATE] = 22; } ; if ((int)ctx.Data[STATE] == 22) { return(new AdapterPresentation(AuthView.AutoLogout, cfgAdfs)); } } // start a new asynchronous RequestSignature AuthRequestDto req = new AuthRequestDto(); req.PhoneNumber = (string)ctx.Data[MSISDN]; req.UserLanguage = (UserLanguage)Enum.Parse(typeof(UserLanguage), resMgr.GetString(RES_LANG, culture)); string uiTrxId = Util.BuildRandomBase64Chars(cfgAdfs.LoginNonceLength); req.DataToBeSigned = _buildMobileIdLoginPrompt(req.UserLanguage, culture, uiTrxId); req.TimeOut = cfgMid.RequestTimeOutSeconds; bool needCheckUserSerialNumber = !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowAbsence) || !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowMismatch) || cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.warnMismatch); if (needCheckUserSerialNumber /* cfgMid.UserSerialNumberPolicy != UserSerialNumberPolicy.ignore */ && ctx.Data.ContainsKey(UKEYSN)) { req.UserSerialNumber = (string)ctx.Data[UKEYSN]; } ctx.Data[AUTHBEGIN] = DateTime.UtcNow.Ticks / 10000; AuthResponseDto rsp = getWebClient().RequestSignature(req, true /* async */); ctx.Data[SESSTRIES] = (int)ctx.Data[SESSTRIES] + 1; string logMsg = "svcStatus:" + (int)rsp.Status.Code + ", mssTransId:\"" + rsp.MsspTransId + "\", state:"; switch (rsp.Status.Code) { case ServiceStatusCode.VALID_SIGNATURE: case ServiceStatusCode.SIGNATURE: ctx.Data[STATE] = 33; ctx.Data[MSSPTRXID] = rsp.MsspTransId; logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + ctx.Data[STATE]); Logging.Log.AuthenticationSuccess(state, (int)ctx.Data[STATE], upn, msspTransId); return(new AdapterPresentation(AuthView.TransferCtx, cfgAdfs)); case ServiceStatusCode.REQUEST_OK: ctx.Data[STATE] = 31; ctx.Data[MSSPTRXID] = rsp.MsspTransId; ctx.Data[DTBS] = req.DataToBeSigned; logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + ctx.Data[STATE]); Logging.Log.AuthenticationContinue(state, (int)ctx.Data[STATE], upn, msspTransId); return(new AdapterPresentation(AuthView.SignRequestSent, cfgAdfs, req.PhoneNumber, uiTrxId, cfgMid.PollResponseDelaySeconds * 1000)); case ServiceStatusCode.USER_CANCEL: ctx.Data[STATE] = 34; logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + ctx.Data[STATE]); Logging.Log.AuthenticationCancel(state, (int)ctx.Data[STATE], upn, msspTransId); return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp)); case ServiceStatusCode.EXPIRED_TRANSACTION: case ServiceStatusCode.PB_SIGNATURE_PROCESS: ctx.Data[STATE] = 35; logger.TraceEvent(TraceEventType.Verbose, 0, logMsg + ctx.Data[STATE]); Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code)); return(new AdapterPresentation(AuthView.RetryOrCancel, cfgAdfs, rsp)); default: ctx.Data[STATE] = 32; logger.TraceEvent((rsp.Status.Color == ServiceStatusColor.Yellow ? TraceEventType.Warning : TraceEventType.Error), 0, logMsg + ctx.Data[STATE] + ", errMsg:\"" + rsp.Status.Message + "\", errDetail:\"" + rsp.Detail + "\""); Logging.Log.AuthenticationTechnicalError(state, (int)ctx.Data[STATE], upn, msspTransId, Enum.GetName(typeof(ServiceStatusCode), rsp.Status.Code), rsp.Detail.ToString()); return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, rsp)); } ; default: logger.TraceEvent(TraceEventType.Error, 0, "BAD_STATE: " + logInfo + ", state:" + state); Logging.Log.AuthenticationFail(state, (int)ctx.Data[STATE], upn, msspTransId, "BAD_STATE"); return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, "action:\"Retry\"; state:" + state)); } } //else if (formAction == "SignOut") //{ // logger.TraceEvent(TraceEventType.Verbose, 0, "SIGNOUT: " + logInfo + "; state:" + state); // return new AdapterPresentation(AuthView.AutoLogout, cfgAdfs); // could lead to endless-loop //} else { logger.TraceEvent(TraceEventType.Error, 0, "Unsupported formAction: " + formAction); Logging.Log.AuthenticationBadForm(state, (int)ctx.Data[STATE], upn, msspTransId, formAction); return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, new AuthResponseDto(ServiceStatusCode.GeneralClientError))); } }
public override object HandlePUT(System.Net.HttpListenerRequest request, ref HTTPResponse response) { response = ObjectsFactories.HTTPResponseFactory.GetObject().CreateCodeNotFound(); return(HTMLResponse(request, ref response)); }
private object HTMLResponse(System.Net.HttpListenerRequest request, ref HTTPResponse response) { return(ObjectsFactories.HTTPResponseFactory.GetObject().CreateCodeNotFound()); }
/// <summary> /// Callback when a HTTP request comes in on the port listener and is handed off /// to a thread for processing. This method /// </summary> /// <param name="result">IAsyncResult containing the HTTPListener</param> protected void ListenerCallback(IAsyncResult result) { try { HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = null; if (listener == null) { Console.WriteLine("Listener null so returning..."); return; } try { // The EndGetContext() method, as with all Begin/End asynchronous methods in the .NET Framework, // blocks until there is a request to be processed or some type of data is available. context = listener.EndGetContext(result); } catch (Exception ex) { // You will get an exception when httpListener.Stop() is called // because there will be a thread stopped waiting on the .EndGetContext() // method, and again, that is just the way most Begin/End asynchronous // methods of the .NET Framework work. Console.WriteLine("HttpListener Stopped: {0}", ex.Message); ReleaseAllLatches(); return; } finally { // Once we know we have a request (or exception), we signal the other thread // so that it calls the BeginGetContext() (or possibly exits if we're not // listening any more) method to start handling the next incoming request // while we continue to process this request on a different thread. listenForNextRequest.Set(); } if (context == null) { return; } Console.WriteLine("HTTP START: {0}", DateTime.Now.ToString()); System.Net.HttpListenerRequest request = context.Request; Console.WriteLine("{0}: {1}", PORT, request.RawUrl); if (request.HasEntityBody) { using (System.IO.StreamReader sr = new System.IO.StreamReader(request.InputStream, request.ContentEncoding)) { string requestData = sr.ReadToEnd(); } } bool debug_enabled = true; if (debug_enabled) { Console.WriteLine(" HTTP User-Agent: {0}", request.UserAgent); foreach (String s in request.Headers.AllKeys) { Console.WriteLine(" Header {0,-10} {1}", s, request.Headers[s]); } } // determine if the client is requesting a compressed response string acceptEncoding = request.Headers["Accept-Encoding"]; bool isCompressed = (!string.IsNullOrEmpty(acceptEncoding) && (acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate"))); Console.WriteLine("Accept-Encoding: {0} Compressed: {1}", acceptEncoding, isCompressed); // Obtain a response object using (System.Net.HttpListenerResponse response = context.Response) { try { response.ContentType = "application/x-dmap-tagged"; response.AddHeader("DAAP-Server", this.GetApplicationName() + " " + this.Version); this.DispatchRequest(request, response, isCompressed); } catch (DACPSecurityException ex) { Console.WriteLine("DACP Security Error: " + ex.Message); response.StatusCode = (int)HttpStatusCode.Forbidden; response.OutputStream.WriteByte(0); } catch (Exception ex) { Console.WriteLine("DACP Server Error: " + ex.Message); response.StatusCode = DACPResponse.MSTT_NO_CONTENT; response.OutputStream.WriteByte(0); } } } catch (Exception httpEx) { Console.WriteLine("DACP Server Error: " + httpEx.Message, httpEx); } Console.WriteLine("HTTP END: {0}", DateTime.Now.ToString()); }
public HttpListenerRequest(HttpListenerContext context) { Request = context.Request; }
public virtual void onPost(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response) { }
public IAdapterPresentation BeginAuthentication(System.Security.Claims.Claim identityClaim, System.Net.HttpListenerRequest request, IAuthenticationContext context) { string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows); System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap(); fileMap.ExeConfigFilename = windir + "\\ADFS\\OktaMFA-ADFS.dll.config"; System.Configuration.Configuration cfg = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None); string oktaTenant = cfg.AppSettings.Settings["Tenant"].Value; string authToken = cfg.AppSettings.Settings["apiKey"].Value; string upn = identityClaim.Value; //string upn = "*****@*****.**"; string baseUrl = oktaTenant + "/api/v1/"; //string tenantName = "marcjordan"; //string baseUrl = "https://" + tenantName + ".oktapreview.com/api/v1/"; //string authToken = "SSWS 009RUU8EeUvD-EpOEH1qHL0OZwmCTJK71kzFjsQufr"; string pinSuccess = "no"; string verifyResult = "false"; string pollingEndpoint = ""; bool isPermanentFailure = false; string message = string.Empty; HttpWebRequest upnRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + upn); upnRequest.Headers.Add("Authorization", authToken); upnRequest.Method = "GET"; upnRequest.ContentType = "application/json"; var upnResponse = (HttpWebResponse)upnRequest.GetResponse(); var idReader = new StreamReader(upnResponse.GetResponseStream()); var id = idReader.ReadToEnd(); RootObject userProfile = JsonConvert.DeserializeObject <RootObject>(id); string userID = userProfile.id.ToString(); HttpWebRequest factorRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors"); factorRequest.Headers.Add("Authorization", authToken); factorRequest.Method = "GET"; factorRequest.ContentType = "application/json"; factorRequest.Accept = "application/json"; var factorResponse = (HttpWebResponse)factorRequest.GetResponse(); var factorReader = new StreamReader(factorResponse.GetResponseStream()); var factorList = factorReader.ReadToEnd(); RootObject[] factors = JsonConvert.DeserializeObject <RootObject[]>(factorList); string factorID = ""; /*foreach (RootObject factor in factors) * if (factor.provider == "OKTA" && factor.factorType == "push") * { * string pushfactorID = factor.id; * HttpWebRequest pushRequest = (HttpWebRequest)WebRequest.Create(baseUrl + "users/" + userID + "/factors/" + pushfactorID + "/verify"); * pushRequest.Headers.Add("Authorization", authToken); * pushRequest.Method = "POST"; * pushRequest.ContentType = "application/json"; * pushRequest.Accept = "application/json"; * pushRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"; * var pushResponse = (HttpWebResponse)pushRequest.GetResponse(); * var pushReader = new StreamReader(pushResponse.GetResponseStream()); * var pushStatus = pushReader.ReadToEnd(); * RootObject pushResult = JsonConvert.DeserializeObject<RootObject>(pushStatus); * pollingEndpoint = pushResult._links.poll.href.ToString(); * }*/ return(new AdapterPresentation(message, upn, isPermanentFailure, pollingEndpoint)); }
/// <summary> /// Called once AD FS decides that MFA is required for a user. /// </summary> /// <param name="identityClaim"></param> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public IAdapterPresentation BeginAuthentication(System.Security.Claims.Claim identityClaim, System.Net.HttpListenerRequest request, IAuthenticationContext context) { // This is needed so we can access the UPN in TryEndAuthentication(). this.identityClaim = identityClaim.Value; return(new AdapterPresentation()); }
// Handle the errors during the authentication process during BeginAuthentication or TryEndAuthentication public IAdapterPresentation OnError(System.Net.HttpListenerRequest request, ExternalAuthenticationException ex) { logger.TraceData(TraceEventType.Error, 0, ex); Logging.Log.AuthenticationGeneralError(ex.Message); return(new AdapterPresentation(AuthView.AuthError, cfgAdfs, ex.Message)); }
protected override bool AuthorizeRequest(System.Net.HttpListenerRequest Request) { return(Request.QueryString["apikey"] != null); }
public override object HandleDELETE(System.Net.HttpListenerRequest request, ref UtilityClasses.HTTPResponse response) { response = ObjectsFactories.HTTPResponseFactory.GetObject().CreateCodeNotImplemented(); return(response); }