org.apache.hadoop.security.authentication.client.KerberosAuthenticator Java Examples

The following examples show how to use org.apache.hadoop.security.authentication.client.KerberosAuthenticator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestDelegationTokenAuthenticationHandlerWithMocks.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private void testManagementOperationErrors() throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getQueryString()).thenReturn(
      DelegationTokenAuthenticator.OP_PARAM + "=" +
          DelegationTokenAuthenticator.DelegationTokenOperation.
              GETDELEGATIONTOKEN.toString()
  );
  Mockito.when(request.getMethod()).thenReturn("FOO");
  Assert.assertFalse(handler.managementOperation(null, request, response));
  Mockito.verify(response).sendError(
      Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),
      Mockito.startsWith("Wrong HTTP method"));

  Mockito.reset(response);
  Mockito.when(request.getMethod()).thenReturn(
      DelegationTokenAuthenticator.DelegationTokenOperation.
          GETDELEGATIONTOKEN.getHttpMethod()
  );
  Assert.assertFalse(handler.managementOperation(null, request, response));
  Mockito.verify(response).setStatus(
      Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED));
  Mockito.verify(response).setHeader(
      Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
      Mockito.eq("mock"));
}
 
Example #2
Source File: TestDelegationTokenAuthenticationHandlerWithMocks.java    From big-c with Apache License 2.0 6 votes vote down vote up
private void testManagementOperationErrors() throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getQueryString()).thenReturn(
      DelegationTokenAuthenticator.OP_PARAM + "=" +
          DelegationTokenAuthenticator.DelegationTokenOperation.
              GETDELEGATIONTOKEN.toString()
  );
  Mockito.when(request.getMethod()).thenReturn("FOO");
  Assert.assertFalse(handler.managementOperation(null, request, response));
  Mockito.verify(response).sendError(
      Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),
      Mockito.startsWith("Wrong HTTP method"));

  Mockito.reset(response);
  Mockito.when(request.getMethod()).thenReturn(
      DelegationTokenAuthenticator.DelegationTokenOperation.
          GETDELEGATIONTOKEN.getHttpMethod()
  );
  Assert.assertFalse(handler.managementOperation(null, request, response));
  Mockito.verify(response).setStatus(
      Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED));
  Mockito.verify(response).setHeader(
      Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
      Mockito.eq("mock"));
}
 
Example #3
Source File: KerberosWebHDFSConnection2.java    From Transwarp-Sample-Code with MIT License 6 votes vote down vote up
public KerberosWebHDFSConnection2(String httpfsUrl, String principal, String password)  {
        this.httpfsUrl = httpfsUrl;
        this.principal = principal;
        this.password = password;

        Configuration conf = new Configuration();
        conf.addResource("conf/hdfs-site.xml");
        conf.addResource("conf/core-site.xml");
        newToken = new AuthenticatedURL.Token();

        KerberosAuthenticator ka = new KerberosAuthenticator();
        ConnectionConfigurator connectionConfigurator = new SSLFactory(SSLFactory.Mode.CLIENT,conf);
        ka.setConnectionConfigurator(connectionConfigurator);

        try{
            URL url = new URL(httpfsUrl);
            ka.authenticate(url,newToken);
        }catch(Exception e){
            e.printStackTrace();
        }


         this.authenticatedURL = new AuthenticatedURL(ka,connectionConfigurator);
//        this.authenticatedURL = new AuthenticatedURL(
//                new KerberosAuthenticator2(principal, password));
    }
 
Example #4
Source File: TestKerberosAuthenticationHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public void testRequestWithoutAuthorization() throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

  Assert.assertNull(handler.authenticate(request, response));
  Mockito.verify(response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
  Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #5
Source File: TestKerberosAuthenticationHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public void testRequestWithInvalidAuthorization() throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

  Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION)).thenReturn("invalid");
  Assert.assertNull(handler.authenticate(request, response));
  Mockito.verify(response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
  Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #6
Source File: KerberosDelegationTokenAuthenticator.java    From big-c with Apache License 2.0 5 votes vote down vote up
public KerberosDelegationTokenAuthenticator() {
  super(new KerberosAuthenticator() {
    @Override
    protected Authenticator getFallBackAuthenticator() {
      return new PseudoDelegationTokenAuthenticator();
    }
  });
}
 
Example #7
Source File: KerberosDelegationTokenAuthenticator.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public KerberosDelegationTokenAuthenticator() {
  super(new KerberosAuthenticator() {
    @Override
    protected Authenticator getFallBackAuthenticator() {
      return new PseudoDelegationTokenAuthenticator();
    }
  });
}
 
Example #8
Source File: TestKerberosAuthenticationHandler.java    From big-c with Apache License 2.0 5 votes vote down vote up
public void testRequestWithoutAuthorization() throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

  Assert.assertNull(handler.authenticate(request, response));
  Mockito.verify(response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
  Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #9
Source File: TestKerberosAuthenticationHandler.java    From big-c with Apache License 2.0 5 votes vote down vote up
public void testRequestWithInvalidAuthorization() throws Exception {
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

  Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION)).thenReturn("invalid");
  Assert.assertNull(handler.authenticate(request, response));
  Mockito.verify(response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
  Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
 
Example #10
Source File: Client.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Initiate client side Kerberos negotiation with the server.
 * @param method method to inject the authentication token into.
 * @param uri the String to parse as a URL.
 * @throws IOException if unknown protocol is found.
 */
private void negotiate(HttpUriRequest method, String uri) throws IOException {
  try {
    AuthenticatedURL.Token token = new AuthenticatedURL.Token();
    KerberosAuthenticator authenticator = new KerberosAuthenticator();
    authenticator.authenticate(new URL(uri), token);
    // Inject the obtained negotiated token in the method cookie
    injectToken(method, token);
  } catch (AuthenticationException e) {
    LOG.error("Failed to negotiate with the server.", e);
    throw new IOException(e);
  }
}
 
Example #11
Source File: TestSentryWebServerWithKerberos.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
@Test
public void testPing() throws Exception {
  runTestAsSubject(new TestOperation(){
    @Override
    public void runTestAsSubject() throws Exception {
      final URL url = new URL("http://"+ SERVER_HOST + ":" + webServerPort + "/ping");
      HttpURLConnection conn = new AuthenticatedURL(new KerberosAuthenticator()).
          openConnection(url, new AuthenticatedURL.Token());
      Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
      String response = IOUtils.toString(conn.getInputStream());
      Assert.assertEquals("pong\n", response);
    }} );
}
 
Example #12
Source File: TestSentryWebServerWithKerberos.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
@Test
public void testPingWithoutSubject() throws Exception {
  final URL url = new URL("http://"+ SERVER_HOST + ":" + webServerPort + "/ping");
  try {
    new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url, new AuthenticatedURL.Token());
    fail("Here should fail.");
  } catch (Exception e) {
    boolean isExpectError = e.getMessage().contains("No valid credentials provided");
    Assert.assertTrue("Here should fail by 'No valid credentials provided'," +
        " but the exception is:" + e, isExpectError);
  }
}
 
Example #13
Source File: TestSentryWebServerWithKerberos.java    From incubator-sentry with Apache License 2.0 5 votes vote down vote up
@Test
public void testPingWithUnauthorizedUser() throws Exception {
  // create an unauthorized User with Kerberos
  String userPrinciple = "user/" + SERVER_HOST;
  String userKerberosName = userPrinciple + "@" + REALM;
  Subject userSubject = new Subject(false, Sets.newHashSet(
      new KerberosPrincipal(userKerberosName)), new HashSet<Object>(),new HashSet<Object>());
  File userKeytab = new File(kdcWorkDir, "user.keytab");
  kdc.createPrincipal(userKeytab, userPrinciple);
  LoginContext userLoginContext = new LoginContext("", userSubject, null,
      KerberosConfiguration.createClientConfig(userKerberosName, userKeytab));
  userLoginContext.login();
  Subject.doAs(userLoginContext.getSubject(), new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      final URL url = new URL("http://"+ SERVER_HOST + ":" + webServerPort + "/ping");
      try {
        new AuthenticatedURL(new KerberosAuthenticator()).openConnection(url, new AuthenticatedURL.Token());
        fail("Here should fail.");
      } catch (AuthenticationException e) {
        String expectedError = "status code: 403";
        if (!e.getMessage().contains(expectedError)) {
          LOG.error("UnexpectedError: " + e.getMessage(), e);
          fail("UnexpectedError: " + e.getMessage());
        }
      }
      return null;
    }
  });
}
 
Example #14
Source File: TestKerberosAuthenticationHandler.java    From hadoop with Apache License 2.0 4 votes vote down vote up
public void testRequestWithAuthorization() throws Exception {
  String token = KerberosTestUtils.doAsClient(new Callable<String>() {
    @Override
    public String call() throws Exception {
      GSSManager gssManager = GSSManager.getInstance();
      GSSContext gssContext = null;
      try {
        String servicePrincipal = KerberosTestUtils.getServerPrincipal();
        Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
        GSSName serviceName = gssManager.createName(servicePrincipal,
            oid);
        oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
        gssContext = gssManager.createContext(serviceName, oid, null,
                                                GSSContext.DEFAULT_LIFETIME);
        gssContext.requestCredDeleg(true);
        gssContext.requestMutualAuth(true);

        byte[] inToken = new byte[0];
        byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length);
        Base64 base64 = new Base64(0);
        return base64.encodeToString(outToken);

      } finally {
        if (gssContext != null) {
          gssContext.dispose();
        }
      }
    }
  });

  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

  Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION))
    .thenReturn(KerberosAuthenticator.NEGOTIATE + " " + token);
  Mockito.when(request.getServerName()).thenReturn("localhost");
  
  AuthenticationToken authToken = handler.authenticate(request, response);

  if (authToken != null) {
    Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                                       Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
    Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);

    Assert.assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName());
    Assert.assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName()));
    Assert.assertEquals(getExpectedType(), authToken.getType());
  } else {
    Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                                       Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
    Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  }
}
 
Example #15
Source File: TestDelegationTokenAuthenticationHandlerWithMocks.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void testRenewToken() throws Exception {
  DelegationTokenAuthenticator.DelegationTokenOperation op =
      DelegationTokenAuthenticator.DelegationTokenOperation.
          RENEWDELEGATIONTOKEN;
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getQueryString()).
      thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString());
  Mockito.when(request.getMethod()).
      thenReturn(op.getHttpMethod());

  Assert.assertFalse(handler.managementOperation(null, request, response));
  Mockito.verify(response).setStatus(
      Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED));
  Mockito.verify(response).setHeader(Mockito.eq(
          KerberosAuthenticator.WWW_AUTHENTICATE),
      Mockito.eq("mock")
  );

  Mockito.reset(response);
  AuthenticationToken token = Mockito.mock(AuthenticationToken.class);
  Mockito.when(token.getUserName()).thenReturn("user");
  Assert.assertFalse(handler.managementOperation(token, request, response));
  Mockito.verify(response).sendError(
      Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),
      Mockito.contains("requires the parameter [token]"));

  Mockito.reset(response);
  StringWriter writer = new StringWriter();
  PrintWriter pwriter = new PrintWriter(writer);
  Mockito.when(response.getWriter()).thenReturn(pwriter);
  Token<DelegationTokenIdentifier> dToken =
      (Token<DelegationTokenIdentifier>) handler.getTokenManager().createToken(
          UserGroupInformation.getCurrentUser(), "user");
  Mockito.when(request.getQueryString()).
      thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString() +
          "&" + DelegationTokenAuthenticator.TOKEN_PARAM + "=" +
          dToken.encodeToUrlString());
  Assert.assertFalse(handler.managementOperation(token, request, response));
  Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
  pwriter.close();
  Assert.assertTrue(writer.toString().contains("long"));
  handler.getTokenManager().verifyToken(dToken);
}
 
Example #16
Source File: TestDelegationTokenAuthenticationHandlerWithMocks.java    From big-c with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void testRenewToken() throws Exception {
  DelegationTokenAuthenticator.DelegationTokenOperation op =
      DelegationTokenAuthenticator.DelegationTokenOperation.
          RENEWDELEGATIONTOKEN;
  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
  Mockito.when(request.getQueryString()).
      thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString());
  Mockito.when(request.getMethod()).
      thenReturn(op.getHttpMethod());

  Assert.assertFalse(handler.managementOperation(null, request, response));
  Mockito.verify(response).setStatus(
      Mockito.eq(HttpServletResponse.SC_UNAUTHORIZED));
  Mockito.verify(response).setHeader(Mockito.eq(
          KerberosAuthenticator.WWW_AUTHENTICATE),
      Mockito.eq("mock")
  );

  Mockito.reset(response);
  AuthenticationToken token = Mockito.mock(AuthenticationToken.class);
  Mockito.when(token.getUserName()).thenReturn("user");
  Assert.assertFalse(handler.managementOperation(token, request, response));
  Mockito.verify(response).sendError(
      Mockito.eq(HttpServletResponse.SC_BAD_REQUEST),
      Mockito.contains("requires the parameter [token]"));

  Mockito.reset(response);
  StringWriter writer = new StringWriter();
  PrintWriter pwriter = new PrintWriter(writer);
  Mockito.when(response.getWriter()).thenReturn(pwriter);
  Token<DelegationTokenIdentifier> dToken =
      (Token<DelegationTokenIdentifier>) handler.getTokenManager().createToken(
          UserGroupInformation.getCurrentUser(), "user");
  Mockito.when(request.getQueryString()).
      thenReturn(DelegationTokenAuthenticator.OP_PARAM + "=" + op.toString() +
          "&" + DelegationTokenAuthenticator.TOKEN_PARAM + "=" +
          dToken.encodeToUrlString());
  Assert.assertFalse(handler.managementOperation(token, request, response));
  Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);
  pwriter.close();
  Assert.assertTrue(writer.toString().contains("long"));
  handler.getTokenManager().verifyToken(dToken);
}
 
Example #17
Source File: TestKerberosAuthenticationHandler.java    From big-c with Apache License 2.0 4 votes vote down vote up
public void testRequestWithAuthorization() throws Exception {
  String token = KerberosTestUtils.doAsClient(new Callable<String>() {
    @Override
    public String call() throws Exception {
      GSSManager gssManager = GSSManager.getInstance();
      GSSContext gssContext = null;
      try {
        String servicePrincipal = KerberosTestUtils.getServerPrincipal();
        Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
        GSSName serviceName = gssManager.createName(servicePrincipal,
            oid);
        oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
        gssContext = gssManager.createContext(serviceName, oid, null,
                                                GSSContext.DEFAULT_LIFETIME);
        gssContext.requestCredDeleg(true);
        gssContext.requestMutualAuth(true);

        byte[] inToken = new byte[0];
        byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length);
        Base64 base64 = new Base64(0);
        return base64.encodeToString(outToken);

      } finally {
        if (gssContext != null) {
          gssContext.dispose();
        }
      }
    }
  });

  HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

  Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION))
    .thenReturn(KerberosAuthenticator.NEGOTIATE + " " + token);
  Mockito.when(request.getServerName()).thenReturn("localhost");
  
  AuthenticationToken authToken = handler.authenticate(request, response);

  if (authToken != null) {
    Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                                       Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
    Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);

    Assert.assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName());
    Assert.assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName()));
    Assert.assertEquals(getExpectedType(), authToken.getType());
  } else {
    Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                                       Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
    Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  }
}