private SecurityMessageProperty ProcessRequiredAuthentication(HttpListenerContext listenerContext) { SecurityMessageProperty property; HttpListenerBasicIdentity identity = null; WindowsIdentity identity2 = null; try { if (this.AuthenticationScheme == AuthenticationSchemes.Basic) { identity = listenerContext.User.Identity as HttpListenerBasicIdentity; property = this.ProcessAuthentication(identity); } else { identity2 = listenerContext.User.Identity as WindowsIdentity; property = this.ProcessAuthentication(identity2, this.GetAuthType(listenerContext)); } } catch (Exception exception) { if (!Fx.IsFatal(exception) && (AuditLevel.Failure == (base.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure))) { this.WriteAuditEvent(AuditLevel.Failure, (identity != null) ? identity.Name : ((identity2 != null) ? identity2.Name : string.Empty), exception); } throw; } if (AuditLevel.Success == (base.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Success)) { this.WriteAuditEvent(AuditLevel.Success, (identity != null) ? identity.Name : ((identity2 != null) ? identity2.Name : string.Empty), null); } return(property); }
private WebUser CheckAuth(HttpListenerContext ctx) { HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)ctx.User.Identity; if (authCache.TryGetValue(identity.Name, out WebUser user)) { if (!Util.Md5(identity.Password).Equals(user.PasswordHash)) { user = Core.Database.GetWebUser(identity.Name, identity.Password); if (user != null) { authCache.Remove(user.Username); authCache.Add(user.Username, user); Core.Database.UpdateLastSeen(user); } } } else { user = Core.Database.GetWebUser(identity.Name, identity.Password); if (user != null) { authCache.Add(user.Username, user); Core.Database.UpdateLastSeen(user); } } return(user); }
public void ShouldConfigure() { XmlConfigurator.Configure(); ILog logger = LogManager.GetLogger(typeof(HttpAppenderTests)); using (var listener = new HttpListener()) { listener.Prefixes.Add("http://localhost:34343/"); listener.AuthenticationSchemes = AuthenticationSchemes.Basic; listener.Start(); try { throw new Exception("KABOOM!"); } catch (Exception e) { logger.Error("Oh noes!", e); } var ctx = listener.GetContext(); using (var reader = new StreamReader(ctx.Request.InputStream)) { var body = reader.ReadToEnd(); Console.WriteLine(body); Assert.IsNotNull(body); HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)ctx.User.Identity; Assert.AreEqual("derp", identity.Name); Assert.AreEqual("darp", identity.Password); } ctx.Response.Close(); } }
/// <summary> /// Validate the client. /// </summary> /// <param name="user">Defines the basic functionality of a principal object.</param> /// <param name="authenticationSchemes">Specifies protocols for authentication.</param> /// <returns>True if the client has been validated; else false.</returns> protected override bool ClientValidation(System.Security.Principal.IPrincipal user, AuthenticationSchemes authenticationSchemes) { // Does the user priciple exist. if (user != null) { // Does the user identity exist. if (user.Identity != null) { // If the client was not authenticated. if (!user.Identity.IsAuthenticated) { return(false); } else { // Select the curent Authentication Schemes switch (authenticationSchemes) { case System.Net.AuthenticationSchemes.Basic | System.Net.AuthenticationSchemes.IntegratedWindowsAuthentication: case System.Net.AuthenticationSchemes.Basic: case System.Net.AuthenticationSchemes.IntegratedWindowsAuthentication: // Specifies Windows authentication. Is the user in the roles // then the users has been valiadted. // If the authentication type is 'IntegratedWindowsAuthentication' if (user.Identity is System.Security.Principal.WindowsIdentity) { WindowsIdentity windowsIdentity = (WindowsIdentity)user.Identity; if (user.IsInRole("Administrators") || user.IsInRole("Users")) { return(true); } else { return(false); } } // If the authentication type is 'Basic' else if (user.Identity is HttpListenerBasicIdentity) { // The username and password are passed for // Basic authentication type. HttpListenerBasicIdentity httpListenerBasicIdentity = (HttpListenerBasicIdentity)user.Identity; string userName = httpListenerBasicIdentity.Name; string password = httpListenerBasicIdentity.Password; return(true); } else { return(false); } default: return(false); } } } } return(false); }
public static MailRuCloud Instance(IHttpContext context) { HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.Session.Principal.Identity; string key = identity.Name + identity.Password; MailRuCloud cloud; if (CloudCache.TryGetValue(key, out cloud)) { if (cloud.CloudApi.Account.Expires <= DateTime.Now) { CloudCache.TryRemove(key, out cloud); } else { return(cloud); } } cloud = new SplittedCloud(identity.Name, identity.Password); if (!CloudCache.TryAdd(key, cloud)) { CloudCache.TryGetValue(key, out cloud); } return(cloud); }
public static MailRuCloud Instance(IHttpContext context) { HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.Session.Principal.Identity; string key = identity.Name + identity.Password; MailRuCloud cloud; if (CloudCache.TryGetValue(key, out cloud)) { if (cloud.CloudApi.Account.Expires <= DateTime.Now) { CloudCache.TryRemove(key, out cloud); } else { return(cloud); } } if (!identity.Name.Contains("@mail.")) { Logger.Warn("Missing domain part (@mail.*) in login, file and folder deleting will be denied"); } cloud = new SplittedCloud(identity.Name, identity.Password); if (!CloudCache.TryAdd(key, cloud)) { CloudCache.TryGetValue(key, out cloud); } return(cloud); }
protected bool isAuthorized(HttpListenerContext context) { if (authorizedUsers == null) { return(true); } // No authorized users provided, allow access to everyone if (authorizedUsers.Count < 1) { return(true); } if (context.User == null) { return(false); } HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity; if (authorizedUsers.ContainsKey(identity.Name)) { if (authorizedUsers[identity.Name] == identity.Password) { return(true); } } return(false); }
public async Task TestHttp_BasicAuthAsync() { const string username = nameof(username); const string password = nameof(password); await this.TestClientServerAsync( async (source, dest) => { await new Download(source, dest, false, Download.AuthType.Basic, username, password, true).PerformAsync(); Assert.That(File.ReadAllBytes(dest), Is.EqualTo(this.contents)); }, context => { HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity; if (identity.Name != username || identity.Password != password) { context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; context.Response.Close(); } context.Response.OutputStream.Write(this.contents, 0, this.contents.Length); context.Response.Close(); }, AuthenticationSchemes.Basic); }
public void Basic1() { #if MONOTOUCH_WATCH Assert.Ignore("HttpListenerBasicIdentity is not supported on watchOS"); #endif HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity(null, null); }
public IHttpContext SetVolume(IHttpContext context) { if (Authentication.Enabled) { HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity; if (!Authentication.VerifyAuthentication(identity)) { context.Response.SendResponse(JsonConvert.SerializeObject(Authentication.FailedAuthentication)); return(context); } } ResponseMessage Response = new ResponseMessage(); Response.Message = "Please input a correct numeric value."; Response.Successful = false; var volume = context.Request.QueryString["level"] ?? JsonConvert.SerializeObject(Response); CoreAudioController controller = new CoreAudioController(); CoreAudioDevice device = controller.DefaultPlaybackDevice; try { device.Volume = Convert.ToDouble(volume); Response.Message = $"Successfully changed volume level to {volume}."; Response.Successful = true; } catch (Exception e) { } context.Response.ContentEncoding = Encoding.Default; context.Response.SendResponse(JsonConvert.SerializeObject(Response)); return(context); }
public IIdentity GetIdentity(IHttpListenerContext context) { try { HttpListenerBasicIdentity ident = (HttpListenerBasicIdentity)context.AdaptedInstance.User.Identity; var isDomainUser = ident.Name.Contains("\\"); var user = ident.Name; var pwd = ident.Password; if (isDomainUser) { return(AuthenticateOnSpecificDomain(user, pwd)); } else { try { using (PrincipalContext authContext = new PrincipalContext(ContextType.Domain)) { if (authContext.ValidateCredentials(user, pwd)) { return(new GenericIdentity(user)); } } } catch (PrincipalException) { } } return(null); } catch (Exception) { return(null); } }
public ClaimsPrincipal JwtHandler(NancyContext Context) { var jwtToken = Context.Request.Headers.Authorization; try { var keyByteArray = Encoding.ASCII.GetBytes(secret); var payload = Jose.JWT.Decode <JwtToken>(jwtToken, keyByteArray); var tokenExpires = FromUnixTime(payload.exp); if (tokenExpires > DateTime.UtcNow) { var identity = new HttpListenerBasicIdentity(payload.sub, null); if (payload.role.Equals("admin")) { identity.AddClaim(new Claim("role", "admin")); } return(new ClaimsPrincipal(identity)); } return(null); } catch (Exception ex) { Console.WriteLine(ex.Message); return(null); } }
public bool TryGetBasicAuthenticationCredentialsFromRequest(HttpRequestMessage request, out HttpListenerBasicIdentity identity) { identity = null; var header = request.Headers.Authorization; if (header != null && header.Scheme.Equals("Basic")) { var encodedUserPass = header.Parameter; var encoding = Encoding.GetEncoding("iso-8859-1"); var userPass = encoding.GetString(Convert.FromBase64String(encodedUserPass)); var separator = userPass.IndexOf(':'); var credentials = new string[2]; credentials[0] = userPass.Substring(0, separator); credentials[1] = userPass.Substring(separator + 1); identity = new HttpListenerBasicIdentity(credentials[0], credentials[1]); return(true); } return(false); }
private bool OnAuthenticate(HttpListenerContext context) { if (context.User == null || context.User.Identity == null) { return(false); } if (!string.IsNullOrWhiteSpace(ServiceSection.Current.WebServer.Login)) { HttpListenerBasicIdentity basic = context.User.Identity as HttpListenerBasicIdentity; if (basic != null) { Host.Log(this, "OnAuthenticate Basic name: " + basic.Name); if (basic.Name == ServiceSection.Current.WebServer.Login && basic.Password == ServiceSection.Current.WebServer.Password) { Host.Log(this, "OnAuthenticate Basic ok"); return(true); } } } if (context.User.Identity.IsAuthenticated) { Host.Log(this, "OnAuthenticate identity (" + context.User.Identity.GetType().FullName + ") name: " + context.User.Identity.Name); return(true); } Host.Log(this, "OnAuthenticate failed"); return(false); }
public IHttpContext Main(IHttpContext context) { if (Authentication.Enabled) { HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity; if (!Authentication.VerifyAuthentication(identity)) { context.Response.SendResponse(JsonConvert.SerializeObject(Authentication.FailedAuthentication)); return(context); } } ResponseMessage response = new ResponseMessage(); response.Message = "Welcome to Windows Rest API."; response.Successful = true; var _Response = new { Reponse = response, HostBindIP = Settings.Default.HostIP, Port = Settings.Default.Port, HTTPS = Settings.Default.HTTPS, StartServer = Settings.Default.StartServer, StartMinimized = Settings.Default.StartMinimized, Authentication = Settings.Default.Authentication, Username = Settings.Default.Username, DetectedEncoding = Encoding.Default.EncodingName, Version = Assembly.GetExecutingAssembly().GetName().Version.ToString() }; context.Response.ContentEncoding = Encoding.Default; context.Response.SendResponse(JsonConvert.SerializeObject(_Response)); return(context); }
private static IPrincipal CopyPrincipal(IPrincipal user) { // Copy IPrincipal to the new WebSocket object. m_User gets disposed when // HttpListenerContext is closed. IPrincipal retVal = null; if (user != null) { if (user as WindowsPrincipal == null) { // authtype Basic HttpListenerBasicIdentity basicIdentity = user.Identity as HttpListenerBasicIdentity; if (basicIdentity != null) { retVal = new GenericPrincipal((new HttpListenerBasicIdentity(basicIdentity.Name, basicIdentity.Password)), null); } } else { // Digest, Negotiate, NTLM WindowsIdentity windowsIdentity = (WindowsIdentity)user.Identity; retVal = new WindowsPrincipal(HttpListener.CreateWindowsIdentity(windowsIdentity.Token, windowsIdentity.AuthenticationType, WindowsAccountType.Normal, true)); } } return(retVal); }
public IHttpContext SendMessage(IHttpContext context) { if (Authentication.Enabled) { HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity; if (!Authentication.VerifyAuthentication(identity)) { context.Response.SendResponse(JsonConvert.SerializeObject(Authentication.FailedAuthentication)); return(context); } } ResponseMessage Response = new ResponseMessage(); Response.Message = "Failed to parse message."; Response.Successful = false; var message = context.Request.QueryString["message"] ?? JsonConvert.SerializeObject(Response); if (message != null || message.Length > 0) { Response.Message = message; Response.Successful = true; Messages.Show(message); } else { Response.Message = "Failed to parse message."; Response.Successful = false; } context.Response.ContentEncoding = Encoding.Default; context.Response.SendResponse(JsonConvert.SerializeObject(Response)); return(context); }
private static MailRuCloud.Api.MailRuCloud CreateCloud(HttpListenerBasicIdentity identity) { Logger.Info($"Cloud instance created for {identity.Name}"); if (!ConstSettings.AvailDomains.Any(d => identity.Name.Contains($"@{d}."))) { string domains = ConstSettings.AvailDomains.Aggregate((c, n) => c + ", @" + n); Logger.Warn($"Missing domain part ({domains}) in login, file and folder deleting will be denied"); } //2FA authorization ITwoFaHandler twoFaHandler = null; if (!string.IsNullOrEmpty(TwoFactorHandlerName)) { twoFaHandler = TwoFaHandlers.Get(TwoFactorHandlerName); if (null == twoFaHandler) { Logger.Error($"Cannot load two-factor auth handler {TwoFactorHandlerName}"); } } var cloud = new MailRuCloud.Api.MailRuCloud(identity.Name, identity.Password, twoFaHandler); return(cloud); }
private void HandleRequest(HttpListenerContext httpListenerContext) { Printer.PrintDiagnostics("Received web request: {0}, raw url: {1}", httpListenerContext.Request.Url, httpListenerContext.Request.RawUrl); if (Config.RequiresAuthentication && !Config.AllowUnauthenticatedRead && Config.SupportsSimpleAuthentication) { HttpListenerBasicIdentity id = (HttpListenerBasicIdentity)httpListenerContext.User.Identity; if (!Config.SimpleAuthentication.CheckUser(id.Name, id.Password)) { httpListenerContext.Response.StatusCode = 401; httpListenerContext.Response.StatusDescription = "Unauthorized"; using (var sr = new System.IO.StreamWriter(httpListenerContext.Response.OutputStream)) sr.Write("<html><head><title>Versionr Server</title></head><body>Unauthorized.</body></html>"); httpListenerContext.Response.Close(); Printer.PrintDiagnostics("Request was unauthorized."); return; } } string uri = httpListenerContext.Request.RawUrl.Substring(Config.WebService.HttpSubdirectory.Length); if (Binaries != null && uri == "/binaries.pack") { httpListenerContext.Response.ContentLength64 = Binaries.Length; httpListenerContext.Response.SendChunked = false; httpListenerContext.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Zip; httpListenerContext.Response.AddHeader("Content-disposition", "attachment; filename=VersionrBinaries.zip"); httpListenerContext.Response.OutputStream.Write(Binaries, 0, Binaries.Length); httpListenerContext.Response.Close(); return; } using (var sr = new System.IO.StreamWriter(httpListenerContext.Response.OutputStream)) sr.Write("<html><head><title>Versionr Server</title></head><body>Omg it works</body></html>"); }
static bool IsAuthorized(HttpListenerBasicIdentity Identity, char Permission) { switch (Permission) { case 'r': if (config.ServerBasicAuth.ReadOnly.Username == Identity.Name && config.ServerBasicAuth.ReadOnly.Password == Identity.Password || config.ServerBasicAuth.ReadWrite.Username == Identity.Name && config.ServerBasicAuth.ReadWrite.Password == Identity.Password) { return(true); } break; case 'w': if (config.ServerBasicAuth.ReadWrite.Username == Identity.Name && config.ServerBasicAuth.ReadWrite.Password == Identity.Password) { return(true); } break; default: return(false); } return(false); }
public IHttpContext ActiveWindow(IHttpContext context) { if (Authentication.Enabled) { HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity; if (!Authentication.VerifyAuthentication(identity)) { context.Response.SendResponse(JsonConvert.SerializeObject(Authentication.FailedAuthentication)); return(context); } } Process[] process = Process.GetProcesses(); ActiveWindow activeWindow = new ActiveWindow(); var strTitle = string.Empty; var handle = GetForegroundWindow(); // Obtain the length of the text var intLength = GetWindowTextLength(handle) + 1; var stringBuilder = new StringBuilder(intLength); if (GetWindowText(handle, stringBuilder, intLength) > 0) { activeWindow.WindowTitle = stringBuilder.ToString(); } else { activeWindow.WindowTitle = null; } foreach (Process p in process) { if (p.MainWindowTitle.Contains(activeWindow.WindowTitle)) { activeWindow.ProcessName = p.ProcessName; activeWindow.StartTime = p.StartTime.ToString(); activeWindow.Response = new ResponseMessage { Message = "Successfully found window.", Successful = true }; break; } else { activeWindow.ProcessName = null; activeWindow.StartTime = null; activeWindow.Response = new ResponseMessage { Message = "Failed to find window.", Successful = false }; } } context.Response.ContentEncoding = Encoding.Default; context.Response.SendResponse(JsonConvert.SerializeObject(activeWindow)); return(context); }
public void GetCredentialsForBasicIdentity_ReturnsUsernameAndPassword(HttpListenerBasicIdentity basic) { KeyValuePair <string, string> credentials = _identityService.GetCredentialsForBasicAuthentication(basic); Assert.True(!string.IsNullOrWhiteSpace(credentials.Key) && !string.IsNullOrWhiteSpace(credentials.Value)); Assert.Equal("username", credentials.Key); Assert.Equal("password", credentials.Value); }
private string ExecuteCommand(string msg, HttpListenerBasicIdentity identity, HttpListenerRequest request, HttpListenerResponse response, Database db) { // check user privilege level int Privilege = db.CheckPrivilege(identity.Name, identity.Password); if (msg == "Login") { return(Privilege.ToString()); } // decode msg and execute serverside code for the command switch (Privilege) { case 0: switch (msg) { case "GetAssignment": return(StudentGetAssignment(identity.Name, request, response, db)); case "StudentGetAssignmentList": return(StudentGetAssignmentList(identity.Name, response, db)); case "AddCompleted": return(StudentAddCompleted(identity.Name, request, db)); case "GetFeedback": return(StudentGetFeedback(identity.Name, request, response, db)); default: return("Invalid command"); } case 1: switch (msg) { case "AddAssignment": return(TeacherAddAssignment(identity.Name, request, db)); case "GetCompletedList": return(TeacherGetCompletedList(request, response, db)); case "GetCompleted": return(TeacherGetCompleted(request, response, db)); case "AddFeedback": return(TeacherAddFeedback(request, db)); case "TeacherGetAssignmentList": return(TeacherGetAssignmentList(identity.Name, response, db)); default: return("Invalid command"); } default: return("Invalid user"); } }
private static async Task DispatchHttpRequestsAsync(HttpListener httpListener, int maxThreadCount = Int32.MaxValue) { // Create a request handler factory that uses basic authentication var requestHandlerFactory = new RequestHandlerFactory(); // Create WebDAV dispatcher var homeFolder = new LocalStore( isEnabledPropFunc: Config.IsEnabledWebDAVProperty, lockingManager: CloudManager.Settings.UseLocks ? (ILockingManager) new InMemoryLockingManager() : new EmptyLockingManager()); var webDavDispatcher = new WebDavDispatcher(homeFolder, requestHandlerFactory); try { using (var sem = new SemaphoreSlim(maxThreadCount)) { var semclo = sem; while (!CancelToken.IsCancellationRequested) { var httpListenerContext = await httpListener.GetContextAsync().ConfigureAwait(false); if (httpListenerContext == null) { break; } HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)httpListenerContext.User.Identity; IHttpContext httpContext = new HttpBasicContext(httpListenerContext, i => i.Name == identity.Name && i.Password == identity.Password); await semclo.WaitAsync(CancelToken.Token); var _ = Task.Run(async() => { try { await webDavDispatcher.DispatchRequestAsync(httpContext) .ConfigureAwait(false); } finally { semclo.Release(); } }, CancelToken.Token); } } } catch (HttpListenerException) when(CancelToken.IsCancellationRequested) { Logger.Info("Server stopped"); } catch (OperationCanceledException) { Logger.Info("Server stopped"); } catch (Exception e) { Logger.Error("Global exception", e); } }
private SecurityMessageProperty ProcessAuthentication(HttpListenerBasicIdentity identity) { SecurityToken token = new UserNameSecurityToken(identity.Name, identity.Password); ReadOnlyCollection <IAuthorizationPolicy> tokenPolicies = this.userNameTokenAuthenticator.ValidateToken(token); return(new SecurityMessageProperty { TransportToken = new SecurityTokenSpecification(token, tokenPolicies), ServiceSecurityContext = new ServiceSecurityContext(tokenPolicies) }); }
public void Basic2() { HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity("", null); Assert.AreEqual("Basic", bi.AuthenticationType, "#01"); Assert.AreEqual("", bi.Name, "#02"); Assert.IsFalse(bi.IsAuthenticated, "#03"); Assert.IsNull(bi.Password, "#04"); }
public IIdentity GetIdentity(IHttpListenerContext context) { HttpListenerBasicIdentity ident = (HttpListenerBasicIdentity)context.AdaptedInstance.User.Identity; string domain = ident.Name.Split('\\')[0]; string username = ident.Name.Split('\\')[1]; var token = GetToken(domain, username, ident.Password); return(new WindowsIdentity(token.DangerousGetHandle())); }
public void Basic4() { HttpListenerBasicIdentity bi = new HttpListenerBasicIdentity("hey", "pass"); Assert.AreEqual("Basic", bi.AuthenticationType, "#01"); Assert.AreEqual("hey", bi.Name, "#02"); Assert.IsTrue(bi.IsAuthenticated, "#03"); Assert.AreEqual("pass", bi.Password, "#04"); }
private static Cloud CreateCloud(HttpListenerBasicIdentity identity) { Logger.Info($"Cloud instance created for {identity.Name}"); var credentials = new Credentials(identity.Name, identity.Password); var cloud = new Cloud(Settings, credentials); return(cloud); }
public IHttpContext SetMonitor(IHttpContext context) { if (Authentication.Enabled) { HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity; if (!Authentication.VerifyAuthentication(identity)) { context.Response.SendResponse(JsonConvert.SerializeObject(Authentication.FailedAuthentication)); return(context); } } ResponseMessage Response = new ResponseMessage(); int sNumber; Response.Message = "Please input windows display number."; Response.Successful = false; var monitor = context.Request.QueryString["primary"] ?? JsonConvert.SerializeObject(Response); try { sNumber = Convert.ToInt16(monitor); switch (sNumber) { case 1: MonitorChanger.SetAsPrimaryMonitor(0); break; case 2: MonitorChanger.SetAsPrimaryMonitor(1); break; case 3: MonitorChanger.SetAsPrimaryMonitor(2); break; case 4: MonitorChanger.SetAsPrimaryMonitor(3); break; } } catch (Exception) { Response.Message = "Are you using a number as input?"; Response.Successful = false; context.Response.SendResponse(JsonConvert.SerializeObject(Response)); return(context); } Response.Message = $"Setting #{sNumber} as primary display."; Response.Successful = true; context.Response.ContentEncoding = Encoding.Default; context.Response.SendResponse(JsonConvert.SerializeObject(Response)); return(context); }
internal IPrincipal ParseBasicAuthentication(string authData) { try { // Basic AUTH Data is a formatted Base64 String //string domain = null; string user = null; string password = null; int pos = -1; string authString = System.Text.Encoding.Default.GetString(Convert.FromBase64String(authData)); // The format is DOMAIN\username:password // Domain is optional pos = authString.IndexOf(':'); // parse the password off the end password = authString.Substring(pos + 1); // discard the password authString = authString.Substring(0, pos); // check if there is a domain pos = authString.IndexOf('\\'); if (pos > 0) { //domain = authString.Substring (0, pos); user = authString.Substring(pos); } else { user = authString; } HttpListenerBasicIdentity identity = new HttpListenerBasicIdentity(user, password); // TODO: What are the roles MS sets return new GenericPrincipal(identity, new string[0]); } catch (Exception) { // Invalid auth data is swallowed silently return null; } }