public static UserState ValidateServerAndUser(ref Uri serverUri, string username, string password) { var pServer = new PanoramaServer(serverUri, username, password); try { var userState = EnsureLogin(pServer); serverUri = pServer.ServerUri; return(userState); } catch (WebException ex) { var response = ex.Response as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.NotFound) // 404 { if (pServer.AddLabKeyContextPath()) { // e.g. Given server URL is https://panoramaweb.org but LabKey Server is not deployed as the root webapp. // Try again with '/labkey' context path return(TryEnsureLogin(pServer, ref serverUri)); } else if (pServer.RemoveContextPath()) { // e.g. User entered the home page of the LabKey Server, running as the root webapp: // https://panoramaweb.org/project/home/begin.view OR https://panoramaweb.org/home/project-begin.view // We will first try https://panoramaweb.org/project/ OR https://panoramaweb.org/home/ as the server URL. // And that will fail. Remove the assumed context path and try again. return(TryEnsureLogin(pServer, ref serverUri)); } } return(UserState.unknown); } }
private static UserState EnsureLogin(PanoramaServer pServer) { var requestUri = new Uri(pServer.ServerUri, ENSURE_LOGIN_PATH); var request = (HttpWebRequest)WebRequest.Create(requestUri); request.Headers.Add(HttpRequestHeader.Authorization, Server.GetBasicAuthHeader(pServer.Username, pServer.Password)); try { using (var response = (HttpWebResponse)request.GetResponse()) { return(response.StatusCode == HttpStatusCode.OK ? UserState.valid : UserState.unknown); } } catch (WebException ex) { var response = ex.Response as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) // 401 { var responseUri = response.ResponseUri; if (!requestUri.Equals(responseUri)) { // This means we were redirected. Authorization headers are not persisted across redirects. Try again // with the responseUri. if (pServer.Redirect(responseUri.AbsoluteUri, ENSURE_LOGIN_PATH)) { return(EnsureLogin(pServer)); } } return(UserState.nonvalid); // User cannot be authenticated } throw; } }
private static UserState TryEnsureLogin(PanoramaServer pServer, ref Uri serverUri) { try { var userState = EnsureLogin(pServer); serverUri = pServer.ServerUri; return(userState); } catch (WebException) { // Due to anything other than 401 (Unauthorized), which is handled in EnsureLogin. return(UserState.unknown); } }