/// <summary> /// Returns an authenticated /// <see cref="HttpURLConnection"/> /// . /// </summary> /// <param name="url">the URL to connect to. Only HTTP/S URLs are supported.</param> /// <param name="token">the authentication token being used for the user.</param> /// <returns> /// an authenticated /// <see cref="HttpURLConnection"/> /// . /// </returns> /// <exception cref="System.IO.IOException">if an IO error occurred.</exception> /// <exception cref="AuthenticationException">if an authentication exception occurred. /// </exception> /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// "/> public virtual HttpURLConnection OpenConnection(Uri url, AuthenticatedURL.Token token ) { if (url == null) { throw new ArgumentException("url cannot be NULL"); } if (!Runtime.EqualsIgnoreCase(url.Scheme, "http") && !Runtime.EqualsIgnoreCase (url.Scheme, "https")) { throw new ArgumentException("url must be for a HTTP or HTTPS resource"); } if (token == null) { throw new ArgumentException("token cannot be NULL"); } authenticator.Authenticate(url, token); HttpURLConnection conn = (HttpURLConnection)url.OpenConnection(); if (connConfigurator != null) { conn = connConfigurator.Configure(conn); } InjectToken(conn, token); return(conn); }
public virtual void TestExtractTokenFail() { HttpURLConnection conn = Org.Mockito.Mockito.Mock <HttpURLConnection>(); Org.Mockito.Mockito.When(conn.GetResponseCode()).ThenReturn(HttpURLConnection.HttpUnauthorized ); string tokenStr = "foo"; IDictionary <string, IList <string> > headers = new Dictionary <string, IList <string> >(); IList <string> cookies = new AList <string>(); cookies.AddItem(AuthenticatedURL.AuthCookie + "=" + tokenStr); headers["Set-Cookie"] = cookies; Org.Mockito.Mockito.When(conn.GetHeaderFields()).ThenReturn(headers); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); token.Set("bar"); try { AuthenticatedURL.ExtractToken(conn, token); NUnit.Framework.Assert.Fail(); } catch (AuthenticationException) { // Expected NUnit.Framework.Assert.IsFalse(token.IsSet()); } catch (Exception) { NUnit.Framework.Assert.Fail(); } }
/// <summary> /// Implements the SPNEGO authentication sequence interaction using the current default principal /// in the Kerberos cache (normally set via kinit). /// </summary> /// <param name="token">the authentication token being used for the user.</param> /// <exception cref="System.IO.IOException">if an IO error occurred.</exception> /// <exception cref="AuthenticationException">if an authentication error occurred.</exception> /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// "/> private void DoSpnegoSequence(AuthenticatedURL.Token token) { try { AccessControlContext context = AccessController.GetContext(); Subject subject = Subject.GetSubject(context); if (subject == null || (subject.GetPrivateCredentials <KerberosKey>().IsEmpty() && subject.GetPrivateCredentials <KerberosTicket>().IsEmpty())) { Log.Debug("No subject in context, logging in"); subject = new Subject(); LoginContext login = new LoginContext(string.Empty, subject, null, new KerberosAuthenticator.KerberosConfiguration ()); login.Login(); } if (Log.IsDebugEnabled()) { Log.Debug("Using subject: " + subject); } Subject.DoAs(subject, new _PrivilegedExceptionAction_287(this)); } catch (PrivilegedActionException ex) { // Loop while the context is still not established throw new AuthenticationException(ex.GetException()); } catch (LoginException ex) { throw new AuthenticationException(ex); } AuthenticatedURL.ExtractToken(conn, token); }
public virtual void TestToken() { AuthenticatedURL.Token token = new AuthenticatedURL.Token(); NUnit.Framework.Assert.IsFalse(token.IsSet()); token = new AuthenticatedURL.Token("foo"); Assert.True(token.IsSet()); Assert.Equal("foo", token.ToString()); }
public virtual void TestInjectToken() { HttpURLConnection conn = Org.Mockito.Mockito.Mock <HttpURLConnection>(); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); token.Set("foo"); AuthenticatedURL.InjectToken(conn, token); Org.Mockito.Mockito.Verify(conn).AddRequestProperty(Org.Mockito.Mockito.Eq("Cookie" ), Org.Mockito.Mockito.AnyString()); }
/* * Check if the passed token is of type "kerberos" or "kerberos-dt" */ /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// "/> private bool IsTokenKerberos(AuthenticatedURL.Token token) { if (token.IsSet()) { AuthToken aToken = AuthToken.Parse(token.ToString()); if (aToken.GetType().Equals("kerberos") || aToken.GetType().Equals("kerberos-dt")) { return(true); } } return(false); }
/// <summary>Helper method that injects an authentication token to send with a connection. /// </summary> /// <param name="conn">connection to inject the authentication token into.</param> /// <param name="token">authentication token to inject.</param> public static void InjectToken(HttpURLConnection conn, AuthenticatedURL.Token token ) { string t = token.token; if (t != null) { if (!t.StartsWith("\"")) { t = "\"" + t + "\""; } conn.AddRequestProperty("Cookie", AuthCookieEq + t); } }
/// <exception cref="System.Exception"/> protected internal virtual void _testAuthentication(Authenticator authenticator, bool doPost) { Start(); try { Uri url = new Uri(GetBaseURL()); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); NUnit.Framework.Assert.IsFalse(token.IsSet()); AuthenticatorTestCase.TestConnectionConfigurator connConf = new AuthenticatorTestCase.TestConnectionConfigurator (); AuthenticatedURL aUrl = new AuthenticatedURL(authenticator, connConf); HttpURLConnection conn = aUrl.OpenConnection(url, token); Assert.True(connConf.invoked); string tokenStr = token.ToString(); if (doPost) { conn.SetRequestMethod("POST"); conn.SetDoOutput(true); } conn.Connect(); if (doPost) { TextWriter writer = new OutputStreamWriter(conn.GetOutputStream()); writer.Write(Post); writer.Close(); } Assert.Equal(HttpURLConnection.HttpOk, conn.GetResponseCode()); if (doPost) { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.GetInputStream ())); string echo = reader.ReadLine(); Assert.Equal(Post, echo); NUnit.Framework.Assert.IsNull(reader.ReadLine()); } aUrl = new AuthenticatedURL(); conn = aUrl.OpenConnection(url, token); conn.Connect(); Assert.Equal(HttpURLConnection.HttpOk, conn.GetResponseCode()); Assert.Equal(tokenStr, token.ToString()); } finally { Stop(); } }
/// <summary>Performs simple authentication against the specified URL.</summary> /// <remarks> /// Performs simple authentication against the specified URL. /// <p> /// If a token is given it does a NOP and returns the given token. /// <p> /// If no token is given, it will perform an HTTP <code>OPTIONS</code> request injecting an additional /// parameter /// <see cref="UserName"/> /// in the query string with the value returned by the /// <see cref="GetUserName()"/> /// method. /// <p> /// If the response is successful it will update the authentication token. /// </remarks> /// <param name="url">the URl to authenticate against.</param> /// <param name="token">the authencation token being used for the user.</param> /// <exception cref="System.IO.IOException">if an IO error occurred.</exception> /// <exception cref="AuthenticationException">if an authentication error occurred.</exception> /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// "/> public virtual void Authenticate(Uri url, AuthenticatedURL.Token token) { string strUrl = url.ToString(); string paramSeparator = (strUrl.Contains("?")) ? "&" : "?"; strUrl += paramSeparator + UserNameEq + GetUserName(); url = new Uri(strUrl); HttpURLConnection conn = (HttpURLConnection)url.OpenConnection(); if (connConfigurator != null) { conn = connConfigurator.Configure(conn); } conn.SetRequestMethod("OPTIONS"); conn.Connect(); AuthenticatedURL.ExtractToken(conn, token); }
public virtual void TestExtractTokenOK() { HttpURLConnection conn = Org.Mockito.Mockito.Mock <HttpURLConnection>(); Org.Mockito.Mockito.When(conn.GetResponseCode()).ThenReturn(HttpURLConnection.HttpOk ); string tokenStr = "foo"; IDictionary <string, IList <string> > headers = new Dictionary <string, IList <string> >(); IList <string> cookies = new AList <string>(); cookies.AddItem(AuthenticatedURL.AuthCookie + "=" + tokenStr); headers["Set-Cookie"] = cookies; Org.Mockito.Mockito.When(conn.GetHeaderFields()).ThenReturn(headers); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); AuthenticatedURL.ExtractToken(conn, token); Assert.Equal(tokenStr, token.ToString()); }
/// <summary>Performs SPNEGO authentication against the specified URL.</summary> /// <remarks> /// Performs SPNEGO authentication against the specified URL. /// <p> /// If a token is given it does a NOP and returns the given token. /// <p> /// If no token is given, it will perform the SPNEGO authentication sequence using an /// HTTP <code>OPTIONS</code> request. /// </remarks> /// <param name="url">the URl to authenticate against.</param> /// <param name="token">the authentication token being used for the user.</param> /// <exception cref="System.IO.IOException">if an IO error occurred.</exception> /// <exception cref="AuthenticationException">if an authentication error occurred.</exception> /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// "/> public virtual void Authenticate(Uri url, AuthenticatedURL.Token token) { if (!token.IsSet()) { this.url = url; base64 = new Base64(0); conn = (HttpURLConnection)url.OpenConnection(); if (connConfigurator != null) { conn = connConfigurator.Configure(conn); } conn.SetRequestMethod(AuthHttpMethod); conn.Connect(); bool needFallback = false; if (conn.GetResponseCode() == HttpURLConnection.HttpOk) { Log.Debug("JDK performed authentication on our behalf."); // If the JDK already did the SPNEGO back-and-forth for // us, just pull out the token. AuthenticatedURL.ExtractToken(conn, token); if (IsTokenKerberos(token)) { return; } needFallback = true; } if (!needFallback && IsNegotiate()) { Log.Debug("Performing our own SPNEGO sequence."); DoSpnegoSequence(token); } else { Log.Debug("Using fallback authenticator sequence."); Authenticator auth = GetFallBackAuthenticator(); // Make sure that the fall back authenticator have the same // ConnectionConfigurator, since the method might be overridden. // Otherwise the fall back authenticator might not have the information // to make the connection (e.g., SSL certificates) auth.SetConnectionConfigurator(connConfigurator); auth.Authenticate(url, token); } } }
/// <summary>Helper method that extracts an authentication token received from a connection. /// </summary> /// <remarks> /// Helper method that extracts an authentication token received from a connection. /// <p> /// This method is used by /// <see cref="Authenticator"/> /// implementations. /// </remarks> /// <param name="conn">connection to extract the authentication token from.</param> /// <param name="token">the authentication token.</param> /// <exception cref="System.IO.IOException">if an IO error occurred.</exception> /// <exception cref="AuthenticationException">if an authentication exception occurred. /// </exception> /// <exception cref="Org.Apache.Hadoop.Security.Authentication.Client.AuthenticationException /// "/> public static void ExtractToken(HttpURLConnection conn, AuthenticatedURL.Token token ) { int respCode = conn.GetResponseCode(); if (respCode == HttpURLConnection.HttpOk || respCode == HttpURLConnection.HttpCreated || respCode == HttpURLConnection.HttpAccepted) { IDictionary <string, IList <string> > headers = conn.GetHeaderFields(); IList <string> cookies = headers["Set-Cookie"]; if (cookies != null) { foreach (string cookie in cookies) { if (cookie.StartsWith(AuthCookieEq)) { string value = Runtime.Substring(cookie, AuthCookieEq.Length); int separator = value.IndexOf(";"); if (separator > -1) { value = Runtime.Substring(value, 0, separator); } if (value.Length > 0) { token.Set(value); } } } } } else { token.Set(null); throw new AuthenticationException("Authentication failed, status: " + conn.GetResponseCode () + ", message: " + conn.GetResponseMessage()); } }