Esempio n. 1
0
  @Test
  public void testRunAsICIR_TwoBeans() throws Exception {
    LoginContext lc = Util.getCLMLoginContext("user1", "password1");
    lc.login();
    try {
      // TODO - Enable once auth checks are working.
      /*
       * try { whoAmIBean.getCallerPrincipal(); fail("Expected call to whoAmIBean to fail"); } catch (Exception expected)
       * { }
       */

      boolean[] response;
      response = entryBean.doubleDoIHaveRole("Users");
      assertTrue(response[0]);
      assertFalse(response[1]);

      response = entryBean.doubleDoIHaveRole("Role1");
      assertTrue(response[0]);
      assertFalse(response[1]);

      response = entryBean.doubleDoIHaveRole("Role2");
      assertFalse(response[0]);
      assertTrue(response[1]);
    } finally {
      lc.logout();
    }

    lc = Util.getCLMLoginContext("user2", "password2");
    lc.login();
    try {
      // Verify the call now passes.
      Principal user = whoAmIBean.getCallerPrincipal();
      assertNotNull(user);

      boolean[] response;
      response = entryBean.doubleDoIHaveRole("Users");
      assertTrue(response[0]);
      assertFalse(response[1]);

      response = entryBean.doubleDoIHaveRole("Role1");
      assertFalse(response[0]);
      assertFalse(response[1]);

      response = entryBean.doubleDoIHaveRole("Role2");
      assertTrue(response[0]);
      assertTrue(response[1]);
    } finally {
      lc.logout();
    }
  }
  @Override
  public void run(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    LoginContext lc = null;
    if (request.getUserPrincipal() == null) {
      try {
        lc = doLogin(request, response);
        request = wrapRequest(request, lc);
      } catch (LoginException e) {
        // login failed
        handleLoginFailure(request, response, e);
        return;
      }
    }

    try {
      chain.doFilter(request, response);
    } finally {
      ClientLoginModule.getThreadLocalLogin().clear();
      if (lc != null) {
        // a null lc may indicate an anonymous login
        try {
          lc.logout();
        } catch (Exception e) {
        }
      }
    }
  }
 /**
  * Re-Login a user in from the ticket cache. This method assumes that login had happened already.
  * The Subject field of this UserGroupInformation object is updated to have the new credentials.
  *
  * @throws IOException on a failure
  */
 public synchronized void reloginFromTicketCache() throws IOException {
   if (!isSecurityEnabled()
       || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS
       || !isKrbTkt) return;
   LoginContext login = getLogin();
   if (login == null) {
     throw new IOException("login must be done first");
   }
   if (!hasSufficientTimeElapsed()) {
     return;
   }
   try {
     LOG.info("Initiating logout for " + getUserName());
     // clear up the kerberos state. But the tokens are not cleared! As per
     // the Java kerberos login module code, only the kerberos credentials
     // are cleared
     login.logout();
     // login and also update the subject field of this instance to
     // have the new credentials (pass it to the LoginContext constructor)
     login = new LoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, getSubject());
     LOG.info("Initiating re-login for " + getUserName());
     login.login();
     setLogin(login);
   } catch (LoginException le) {
     throw new IOException("Login failure for " + getUserName(), le);
   }
 }
 @Test
 public void testRoleExpansion() throws LoginException {
   LoginContext context =
       new LoginContext(
           "ExpandedLDAPLogin",
           new CallbackHandler() {
             public void handle(Callback[] callbacks)
                 throws IOException, UnsupportedCallbackException {
               for (int i = 0; i < callbacks.length; i++) {
                 if (callbacks[i] instanceof NameCallback) {
                   ((NameCallback) callbacks[i]).setName("first");
                 } else if (callbacks[i] instanceof PasswordCallback) {
                   ((PasswordCallback) callbacks[i]).setPassword("secret".toCharArray());
                 } else {
                   throw new UnsupportedCallbackException(callbacks[i]);
                 }
               }
             }
           });
   context.login();
   Subject subject = context.getSubject();
   boolean isAdmin = false;
   boolean isUser = false;
   for (Principal principal : subject.getPrincipals()) {
     if (principal instanceof GroupPrincipal) {
       GroupPrincipal groupPrincipal = (GroupPrincipal) principal;
       if (groupPrincipal.getName().equalsIgnoreCase("admins")) isAdmin = true;
       if (groupPrincipal.getName().equalsIgnoreCase("users")) isUser = true;
     }
   }
   // Should be in users by virtue of being in admins
   assertTrue(isAdmin && isUser);
   context.logout();
 }
Esempio n. 5
0
  @After
  public void tearDown() throws Exception {

    AccessorUtil.getRuntimeAPI().deleteAllProcessInstances(bonitaProcess.getUUID());
    AccessorUtil.getManagementAPI().disable(bonitaProcess.getUUID());
    AccessorUtil.getManagementAPI().deleteProcess(bonitaProcess.getUUID());

    loginContext.logout();
  }
 public void logoutSubject() {
   if (loginContext != null) {
     try {
       loginContext.logout();
     } catch (LoginException le) {
       logger.error("Failed to logout kerberos subject", le);
     }
   }
 }
Esempio n. 7
0
 protected void closeLocalLogin(LoginContext lc) throws AgencyException {
   try {
     lc.logout();
   } catch (LoginException e) {
     System.out.println("ERROR logout in WS");
     throw new AgencyException(
         "Couldn't connect with the login service [LoginContext]. Contact your service provider.",
         e);
   }
 }
Esempio n. 8
0
 /* ------------------------------------------------------------ */
 public void logout(UserIdentity user) {
   Set<JAASUserPrincipal> userPrincipals =
       user.getSubject().getPrincipals(JAASUserPrincipal.class);
   LoginContext loginContext = userPrincipals.iterator().next().getLoginContext();
   try {
     loginContext.logout();
   } catch (LoginException e) {
     LOG.warn(e);
   }
 }
Esempio n. 9
0
 /**
  * Call the logout method on the Jaas Login Module Set the username and currentRowkey to null for
  * clean up purposes
  */
 public boolean logout() {
   try {
     usuarioLogged = null;
     FacesContext facesContext = FacesContext.getCurrentInstance();
     HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
     context.logout();
     session.invalidate();
   } catch (Exception e) {
     log("SessionBean1::Exception occured while logging out" + e.getMessage());
     error("Error Loggin out");
     return false;
   }
   return true;
 }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    HttpSession httpSession = request.getSession();

    LoginContext lc = (LoginContext) httpSession.getAttribute("LoginContext");
    try {
      System.out.println("INVOCO IL LOGOUT");
      lc.logout();
    } catch (LoginException e) {
      e.printStackTrace();
    }

    response.sendRedirect(response.encodeRedirectURL("/JAAS_XACML_Exercise2/public/logout.jsp"));
  }
Esempio n. 11
0
 public static void verifyPassword(String principal, String password) throws LoginException {
   LoginContext lc = null;
   try {
     lc = Krb5Login.withPassword(principal, password);
     lc.login();
   } finally {
     if (lc != null) {
       try {
         lc.logout();
       } catch (LoginException le) {
         ZimbraLog.account.warn("krb5 logout failed", le);
       }
     }
   }
 }
  public void generate() throws SAXException, ProcessingException {
    if (log.isDebugEnabled()) log.debug("begin generate");
    contentHandler.startDocument();
    Document doc = XercesHelper.getNewDocument();
    Element root = doc.createElement("authentication");
    doc.appendChild(root);
    try {
      LoginContext lc = new LoginContext(jaasRealm, new InternalCallbackHandler());
      lc.login();
      Subject s = lc.getSubject();
      if (log.isDebugEnabled()) log.debug("Subject is: " + s.getPrincipals().toString());
      Element idElement = doc.createElement("ID");
      root.appendChild(idElement);

      Iterator it = s.getPrincipals(java.security.Principal.class).iterator();
      while (it.hasNext()) {
        Principal prp = (Principal) it.next();
        if (prp.getName().equalsIgnoreCase("Roles")) {
          Element roles = doc.createElement("roles");
          root.appendChild(roles);
          Group grp = (Group) prp;
          Enumeration member = grp.members();
          while (member.hasMoreElements()) {
            Principal sg = (Principal) member.nextElement();
            Element role = doc.createElement("role");
            roles.appendChild(role);
            Text txt = doc.createTextNode(sg.getName());
            role.appendChild(txt);
          }
        } else {
          Node nde = doc.createTextNode(prp.getName());
          idElement.appendChild(nde);
        }
      }
      lc.logout();
    } catch (Exception exe) {
      log.warn("Could not login user \"" + userid + "\"");
    } finally {
      try {
        DOMStreamer ds = new DOMStreamer(contentHandler);
        ds.stream(doc.getDocumentElement());
        contentHandler.endDocument();
      } catch (Exception exe) {
        log.error("Error streaming to dom", exe);
      }
      if (log.isDebugEnabled()) log.debug("end generate");
    }
  }
Esempio n. 13
0
 @Test
 public void testAuthentication_TwoBeans() throws Exception {
   LoginContext lc = Util.getCLMLoginContext("user1", "password1");
   lc.login();
   try {
     String[] response = entryBean.doubleWhoAmI();
     assertEquals("user1", response[0]);
     assertEquals(
         "anonymous",
         response[
             1]); // Unless a run-as-principal configuration has been done, you cannot expect a
                  // principal
   } finally {
     lc.logout();
   }
 }
Esempio n. 14
0
  /**
   * This provides command line access to this JAAS module.
   *
   * @param args command line arguments
   * @throws Exception if an error occurs
   */
  public static void main(final String[] args) throws Exception {
    String name = "ldaptive";
    if (args.length > 0) {
      name = args[0];
    }

    final LoginContext lc = new LoginContext(name, new TextCallbackHandler());
    lc.login();
    System.out.println("Authentication/Authorization succeeded");

    final Set<Principal> principals = lc.getSubject().getPrincipals();
    System.out.println("Subject Principal(s): ");

    for (Principal p : principals) {
      System.out.println("  " + p);
    }
    lc.logout();
  }
Esempio n. 15
0
  /** Migration test from EJB Testsuite (security/TimerRunAs) to AS7 [JBQA-5483]. */
  @Test
  public void testTimerNoSecurityAssociationPrincipal() throws Exception {
    LoginContext lc = Util.getCLMLoginContext("user1", "password1");
    lc.login();

    try {
      TimerTester test =
          (TimerTester) ctx.lookup("java:module/" + TimerTesterBean.class.getSimpleName());

      assertNotNull(test);
      test.startTimer(150);
      Assert.assertTrue(TimerTesterBean.awaitTimerCall());

      Assert.assertEquals(
          "user2", TimerTesterBean.calleeCallerPrincipal.iterator().next().getName());
    } finally {
      lc.logout();
    }
  }
Esempio n. 16
0
  public static void main(final String[] args) throws Exception {

    // Domain (pre-authentication) account
    //        final String username = "******"; // For Non-WIA authentication against
    // libre Kerberos/LDAP servers
    final String username = "******";

    // Password for the pre-auth acct.
    final String password = "******";

    // Name of our krb5 config file
    final String krbfile = "/etc/krb5.conf";

    // Name of our login config file
    final String loginfile = "src/main/conf/spnego.conf";

    // Name of our login module
    final String module = "spnego-client";

    // set some system properties
    System.setProperty("java.security.krb5.conf", krbfile);
    System.setProperty("java.security.auth.login.config", loginfile);
    System.setProperty("sun.security.krb5.debug", "true");

    // assert
    HelloKDC.validate(username, password, krbfile, loginfile, module);

    final CallbackHandler handler = HelloKDC.getUsernamePasswordHandler(username, password);

    final LoginContext loginContext = new LoginContext(module, handler);

    // attempt to login
    loginContext.login();

    // output some info
    System.out.println("Subject=" + loginContext.getSubject());

    // logout
    loginContext.logout();

    System.out.println("Connection test successful.");
  }
  @Test
  public void testLdapExample1() throws Exception {
    System.out.println("testLdapExample1");
    UsernamePasswordHandler handler = new UsernamePasswordHandler("josuna", "123".toCharArray());
    LoginContext lc = new LoginContext("testLdapExample1", handler);
    lc.login();

    Subject subject = lc.getSubject();

    System.out.println("Subject: " + subject);

    Set groups = subject.getPrincipals(Group.class);
    assertTrue(
        "Principals contains josuna",
        subject.getPrincipals().contains(new SimplePrincipal("josuna")));
    Group roles = (Group) groups.iterator().next();
    assertTrue("adminoper is a role", roles.isMember(new SimplePrincipal("adminoper")));

    lc.logout();
  }
Esempio n. 18
0
  /**
   * This provides command line access to a <code>LdapLoginModule</code>.
   *
   * @param args <code>String[]</code>
   * @throws Exception if an error occurs
   */
  public static void main(final String[] args) throws Exception {
    String name = "vt-ldap";
    if (args.length > 0) {
      name = args[0];
    }

    final LoginContext lc = new LoginContext(name, new TextCallbackHandler());
    lc.login();
    System.out.println("Authentication/Authorization succeeded");

    final Set<Principal> principals = lc.getSubject().getPrincipals();
    System.out.println("Subject Principal(s): ");

    final Iterator<Principal> i = principals.iterator();
    while (i.hasNext()) {
      final Principal p = i.next();
      System.out.println("  " + p);
    }
    lc.logout();
  }
Esempio n. 19
0
 public void deleteInstance(String instanceUID) throws Exception {
   Context context = new InitialContext();
   String icmaaetitle = (String) context.lookup("java:global/ICMAAETITLE");
   LoginContext lctx = new LoginContext(icmaaetitle, null, pacsHandler, conf);
   lctx.login();
   InitialContext ctx = new InitialContext(env);
   MBeanServerConnection mconn = (MBeanServerConnection) ctx.lookup("jmx/invoker/RMIAdaptor");
   ObjectName contentEditName = new ObjectName("dcm4chee.archive:service=ContentEditService");
   String[] inst = {instanceUID};
   // mconn.invoke(contentEditName, "moveInstanceToTrash", new Object[] {
   // instanceUID }, new String[] { String.class.getName() });
   mconn.invoke(
       contentEditName,
       "moveInstancesToTrash",
       new Object[] {inst},
       new String[] {String[].class.getName()});
   mconn.invoke(contentEditName, "emptyTrash", null, null);
   lctx.logout();
   // System.out.println("Successfully deleted image "+instanceUID);
 }
Esempio n. 20
0
  public static void performAs(String principal, String keytab, PrivilegedExceptionAction action)
      throws PrivilegedActionException, LoginException {
    LoginContext lc = null;
    try {
      // Authenticate to Kerberos.
      lc = Krb5Login.withKeyTab(principal, keytab);
      lc.login();

      // Assume the identity of the authenticated principal.
      Subject.doAs(lc.getSubject(), action);

    } finally {
      if (lc != null) {
        try {
          lc.logout();
        } catch (LoginException le) {
          ZimbraLog.account.warn("krb5 logout failed", le);
        }
      }
    }
  }
Esempio n. 21
0
  /**
   * Calls the {@link #run()} method with an unrestricted {@link #session}. During this call, {@link
   * #isUnrestricted} is set to {@code true}.
   */
  public void runUnrestricted() {
    isUnrestricted = true;
    try {
      if (sessionIsAlreadyUnrestricted) {
        run();
        return;
      }

      LoginContext loginContext;
      try {
        loginContext = Framework.loginAs(originatingUsername);
      } catch (LoginException e) {
        throw new NuxeoException(e);
      }
      try {
        CoreSession baseSession = session;
        session = CoreInstance.openCoreSession(repositoryName);
        try {
          run();
        } finally {
          try {
            session.close();
          } finally {
            session = baseSession;
          }
        }
      } finally {
        try {
          // loginContext may be null in tests
          if (loginContext != null) {
            loginContext.logout();
          }
        } catch (LoginException e) {
          throw new NuxeoException(e);
        }
      }
    } finally {
      isUnrestricted = false;
    }
  }
 /**
  * Re-Login a user in from a keytab file. Loads a user identity from a keytab file and logs them
  * in. They become the currently logged-in user. This method assumes that {@link
  * #loginUserFromKeytab(String, String)} had happened already. The Subject field of this
  * UserGroupInformation object is updated to have the new credentials.
  *
  * @throws IOException on a failure
  */
 public synchronized void reloginFromKeytab() throws IOException {
   if (!isSecurityEnabled()
       || user.getAuthenticationMethod() != AuthenticationMethod.KERBEROS
       || !isKeytab) return;
   LoginContext login = getLogin();
   if (login == null || keytabFile == null) {
     throw new IOException("loginUserFromKeyTab must be done first");
   }
   if (!hasSufficientTimeElapsed()) {
     return;
   }
   long start = 0;
   try {
     LOG.info("Initiating logout for " + getUserName());
     synchronized (UserGroupInformation.class) {
       // clear up the kerberos state. But the tokens are not cleared! As per
       // the Java kerberos login module code, only the kerberos credentials
       // are cleared
       login.logout();
       // login and also update the subject field of this instance to
       // have the new credentials (pass it to the LoginContext constructor)
       login = new LoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, getSubject());
       LOG.info("Initiating re-login for " + keytabPrincipal);
       start = System.currentTimeMillis();
       login.login();
       metrics.loginSuccess.inc(System.currentTimeMillis() - start);
       setLogin(login);
     }
   } catch (LoginException le) {
     if (start > 0) {
       metrics.loginFailure.inc(System.currentTimeMillis() - start);
     }
     throw new IOException(
         "Login failure for " + keytabPrincipal + " from keytab " + keytabFile, le);
   }
 }
Esempio n. 23
0
 public void logout() throws LoginException {
   context.logout();
 }
Esempio n. 24
0
 public OracleUser(LoginContext context) throws LoginException {
   this.context = context;
   context.logout();
   context.login();
   this.subject = context.getSubject();
 }
  /**
   * Test Right Throw 2 events matching by one queue, but user can read only one event
   *
   * @throws MembershipServiceException
   * @throws GreetingServiceException
   * @throws EventQueueServiceException
   * @throws InterruptedException
   * @throws LoginException
   */
  @Test(timeout = 50000)
  public void testNotificationRightEvent()
      throws MembershipServiceException, GreetingServiceException, EventQueueServiceException,
          InterruptedException, LoginException {
    logger.info("testNotificationRightEvent() called");
    String caller = membership.getProfilePathForConnectedIdentifier();

    // root permit to kermit to create something on /
    greeting.giveAutorization("/", "/profiles/kermit", new String[] {"create"});

    loginContext.logout();

    // login kermit
    UsernamePasswordHandler uph = new UsernamePasswordHandler("kermit", "thefrog");
    loginContext = new LoginContext("qualipso", uph);
    loginContext.login();

    // kermit create a folder and a resource on this folder and
    // create a read event on this name
    greeting.createFolder("/kermitFolder", "kermitFolder");
    greeting.createName("/kermitFolder/kermitName", "kermitName");
    greeting.readName("/kermitFolder/kermitName");
    greeting.deleteName("/kermitFolder/kermitName");
    greeting.deleteFolder("/kermitFolder");

    loginContext.logout();

    uph = new UsernamePasswordHandler("root", AllTests.ROOT_ACCOUNT_PASS);
    loginContext = new LoginContext("qualipso", uph);
    loginContext.login();

    greeting.readName(pathResource);

    Event[] lEvent2 = new Event[] {};

    while (lEvent2.length < 1) {
      lEvent2 = eqs.getEvents(pathQueue2);
    }

    assertTrue(
        "TestNotificationRighEvent : expected 1 events into queue2("
            + pathQueue2
            + ") but found "
            + lEvent2.length,
        lEvent2.length == 1);
    Event e = lEvent2[0];
    assertEquals(
        "TestNotificationRighEvent : event resource expected "
            + pathResource
            + " but found "
            + e.getFromResource(),
        e.getFromResource(),
        pathResource);
    assertEquals(
        "TestNotificationRighEvent : event type expected greeting.name.create but found "
            + e.getEventType(),
        e.getEventType(),
        "greeting.name.read");
    assertEquals(
        "TestNotificationRighEvent : event throwedBy expected "
            + caller
            + " but found"
            + e.getThrowedBy(),
        e.getThrowedBy(),
        caller);

    Thread.sleep(60);

    assertTrue(
        "TestNotificationRighEvent : expected 1 event into queue1 but found "
            + eqs.getEvents(pathQueue2).length,
        eqs.getEvents(pathQueue2).length == 1);
  }
Esempio n. 26
0
 /**
  * Calls logout, if necessary, on any associated JAASLoginContext. May in the future be extended
  * to cover other logout requirements.
  *
  * @throws Exception If something goes wrong with the logout. Uses Exception to allow for future
  *     expansion of this method to cover other logout mechanisms that might throw a different
  *     exception to LoginContext
  */
 public void logout() throws Exception {
   if (loginContext != null) {
     loginContext.logout();
   }
 }
Esempio n. 27
0
  /**
   * Returns response body for the given URL request as a String. It also checks if the returned
   * HTTP status code is the expected one. If the server returns {@link
   * HttpServletResponse#SC_UNAUTHORIZED} and an username is provided, then the given user is
   * authenticated against Kerberos and a new request is executed under the new subject.
   *
   * @param uri URI to which the request should be made
   * @param user Username
   * @param pass Password
   * @param expectedStatusCode expected status code returned from the requested server
   * @return HTTP response body
   * @throws IOException
   * @throws URISyntaxException
   * @throws PrivilegedActionException
   * @throws LoginException
   */
  public static String makeCallWithKerberosAuthn(
      final URI uri, final String user, final String pass, final int expectedStatusCode)
      throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    LOGGER.info("Requesting URI: " + uri);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
      httpClient
          .getAuthSchemes()
          .register(AuthPolicy.SPNEGO, new JBossNegotiateSchemeFactory(true));
      httpClient
          .getCredentialsProvider()
          .setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());

      final HttpGet httpGet = new HttpGet(uri);
      final HttpResponse response = httpClient.execute(httpGet);
      int statusCode = response.getStatusLine().getStatusCode();
      if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
        assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
      }
      final HttpEntity entity = response.getEntity();
      final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
      assertTrue(
          "WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
      final Set<String> authnHeaderValues = new HashSet<String>();
      for (final Header header : authnHeaders) {
        authnHeaderValues.add(header.getValue());
      }
      assertTrue(
          "WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));

      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
      }
      if (entity != null) EntityUtils.consume(entity);

      // Use our custom configuration to avoid reliance on external config
      Configuration.setConfiguration(new Krb5LoginConfiguration());
      // 1. Authenticate to Kerberos.
      final LoginContext lc =
          new LoginContext(Utils.class.getName(), new UsernamePasswordHandler(user, pass));
      lc.login();

      // 2. Perform the work as authenticated Subject.
      final String responseBody =
          Subject.doAs(
              lc.getSubject(),
              new PrivilegedExceptionAction<String>() {
                public String run() throws Exception {
                  final HttpResponse response = httpClient.execute(httpGet);
                  int statusCode = response.getStatusLine().getStatusCode();
                  assertEquals(
                      "Unexpected status code returned after the authentication.",
                      expectedStatusCode,
                      statusCode);
                  return EntityUtils.toString(response.getEntity());
                }
              });
      lc.logout();
      return responseBody;
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpClient.getConnectionManager().shutdown();
    }
  }
Esempio n. 28
0
  /**
   * Creates request against SPNEGO protected web-app with FORM fallback. It tries to login using
   * SPNEGO first - if it fails, FORM is used.
   *
   * @param contextUrl
   * @param page
   * @param user
   * @param pass
   * @param expectedStatusCode
   * @return
   * @throws IOException
   * @throws URISyntaxException
   * @throws PrivilegedActionException
   * @throws LoginException
   */
  public static String makeHttpCallWithFallback(
      final String contextUrl,
      final String page,
      final String user,
      final String pass,
      final int expectedStatusCode)
      throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
    final String url = strippedContextUrl + page;
    LOGGER.info("Requesting URL: " + url);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectStrategy(REDIRECT_STRATEGY);
    String unauthorizedPageBody = null;
    try {
      httpClient
          .getAuthSchemes()
          .register(AuthPolicy.SPNEGO, new JBossNegotiateSchemeFactory(true));
      httpClient
          .getCredentialsProvider()
          .setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());

      final HttpGet httpGet = new HttpGet(url);
      final HttpResponse response = httpClient.execute(httpGet);
      int statusCode = response.getStatusLine().getStatusCode();
      if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
        assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
      }
      final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
      assertTrue(
          "WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
      final Set<String> authnHeaderValues = new HashSet<String>();
      for (final Header header : authnHeaders) {
        authnHeaderValues.add(header.getValue());
      }
      assertTrue(
          "WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));

      LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
      unauthorizedPageBody = EntityUtils.toString(response.getEntity());

      // Use our custom configuration to avoid reliance on external config
      Configuration.setConfiguration(new Krb5LoginConfiguration());
      // 1. Authenticate to Kerberos.
      final LoginContext lc =
          new LoginContext(Utils.class.getName(), new UsernamePasswordHandler(user, pass));
      lc.login();

      // 2. Perform the work as authenticated Subject.
      final String responseBody =
          Subject.doAs(
              lc.getSubject(),
              new PrivilegedExceptionAction<String>() {
                public String run() throws Exception {
                  final HttpResponse response = httpClient.execute(httpGet);
                  int statusCode = response.getStatusLine().getStatusCode();
                  assertEquals(
                      "Unexpected status code returned after the authentication.",
                      expectedStatusCode,
                      statusCode);
                  return EntityUtils.toString(response.getEntity());
                }
              });
      lc.logout();
      return responseBody;
    } catch (LoginException e) {
      assertNotNull(unauthorizedPageBody);
      assertTrue(unauthorizedPageBody.contains("j_security_check"));

      HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      nameValuePairs.add(new BasicNameValuePair("j_username", user));
      nameValuePairs.add(new BasicNameValuePair("j_password", pass));
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      final HttpResponse response = httpClient.execute(httpPost);
      int statusCode = response.getStatusLine().getStatusCode();
      assertEquals(
          "Unexpected status code returned after the authentication.",
          expectedStatusCode,
          statusCode);
      return EntityUtils.toString(response.getEntity());
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpClient.getConnectionManager().shutdown();
    }
  }
Esempio n. 29
0
  @SuppressWarnings("unchecked")
  public static void main(String[] args) throws Exception {
    args = siftArgs(args);

    System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, "org.apache.openejb.client");

    // the new initial context is automatically hooked up to the server side
    // java:openejb/client/${clientModuleId} tree
    final InitialContext initialContext = new InitialContext();

    // path to the client jar file
    final String path = (String) initialContext.lookup("java:info/path");
    // TODO: Download the file
    final File file = new File(path);

    // Create a child class loader containing the application jar
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader == null) {
      classLoader = new URLClassLoader(new URL[] {file.toURI().toURL()});
    } else {
      classLoader = new URLClassLoader(new URL[] {file.toURI().toURL()}, classLoader);
    }
    Thread.currentThread().setContextClassLoader(classLoader);

    // load the main class and get the main method
    // do this first so we fail fast on a bad class path
    final String mainClassName = (String) initialContext.lookup("java:info/mainClass");
    final Class mainClass = classLoader.loadClass(mainClassName);
    final Method mainMethod = mainClass.getMethod("main", String[].class);

    // load the callback handler class
    // again do this before any major work so we can fail fase
    Class callbackHandlerClass = null;
    try {
      final String callbackHandlerName =
          (String) initialContext.lookup("java:info/callbackHandler");
      callbackHandlerClass = classLoader.loadClass(callbackHandlerName);
    } catch (NameNotFoundException ignored) {
    }

    final InjectionMetaData injectionMetaData =
        (InjectionMetaData) initialContext.lookup("java:info/injections");
    ClientInstance.get().setComponent(InjectionMetaData.class, injectionMetaData);
    for (final Injection injection : injectionMetaData.getInjections()) {
      try {
        final Object value = initialContext.lookup("java:" + injection.getJndiName());
        final Class target = classLoader.loadClass(injection.getTargetClass());
        final Field field = target.getDeclaredField(injection.getName());
        setAccessible(field);
        field.set(null, value);
      } catch (Throwable e) {
        //noinspection UseOfSystemOutOrSystemErr
        System.err.println(
            "Injection FAILED: class="
                + injection.getTargetClass()
                + ", name="
                + injection.getName()
                + ", jndi-ref="
                + injection.getJndiName());
        e.printStackTrace();
      }
    }

    // if there is no security then just call the main method
    final Object[] mainArgs = new Object[] {args};
    if (callbackHandlerClass == null) {
      invoke(mainMethod, mainArgs);
    } else {
      // create the callback handler
      final CallbackHandler callbackHandler = (CallbackHandler) callbackHandlerClass.newInstance();

      // initialize the jaas system
      loadJassLoginConfig(classLoader);

      // login
      final LoginContext loginContext = new LoginContext("ClientLogin", callbackHandler);
      loginContext.login();

      // success - get the subject
      final Subject subject = loginContext.getSubject();

      // call the main method in a doAs so the subject is associated with the thread
      try {
        Subject.doAs(
            subject,
            new PrivilegedExceptionAction() {
              public Object run() throws Exception {
                invoke(mainMethod, mainArgs);
                return null;
              }
            });
      } finally {
        // And finally, logout
        loginContext.logout();
      }
    }
  }
Esempio n. 30
0
  @Override
  public boolean authenticate(Request request, HttpServletResponse response, LoginConfig config)
      throws IOException {

    if (checkForCachedAuthentication(request, response, true)) {
      return true;
    }

    MessageBytes authorization =
        request.getCoyoteRequest().getMimeHeaders().getValue("authorization");

    if (authorization == null) {
      if (log.isDebugEnabled()) {
        log.debug(sm.getString("authenticator.noAuthHeader"));
      }
      response.setHeader("WWW-Authenticate", "Negotiate");
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return false;
    }

    authorization.toBytes();
    ByteChunk authorizationBC = authorization.getByteChunk();

    if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) {
      if (log.isDebugEnabled()) {
        log.debug(sm.getString("spnegoAuthenticator.authHeaderNotNego"));
      }
      response.setHeader("WWW-Authenticate", "Negotiate");
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return false;
    }

    authorizationBC.setOffset(authorizationBC.getOffset() + 10);

    byte[] decoded =
        Base64.decodeBase64(
            authorizationBC.getBuffer(), authorizationBC.getOffset(), authorizationBC.getLength());

    if (getApplyJava8u40Fix()) {
      SpnegoTokenFixer.fix(decoded);
    }

    if (decoded.length == 0) {
      if (log.isDebugEnabled()) {
        log.debug(sm.getString("spnegoAuthenticator.authHeaderNoToken"));
      }
      response.setHeader("WWW-Authenticate", "Negotiate");
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return false;
    }

    LoginContext lc = null;
    GSSContext gssContext = null;
    byte[] outToken = null;
    Principal principal = null;
    try {
      try {
        lc = new LoginContext(getLoginConfigName());
        lc.login();
      } catch (LoginException e) {
        log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return false;
      }

      Subject subject = lc.getSubject();

      // Assume the GSSContext is stateless
      // TODO: Confirm this assumption
      final GSSManager manager = GSSManager.getInstance();
      // IBM JDK only understands indefinite lifetime
      final int credentialLifetime;
      if (Globals.IS_IBM_JVM) {
        credentialLifetime = GSSCredential.INDEFINITE_LIFETIME;
      } else {
        credentialLifetime = GSSCredential.DEFAULT_LIFETIME;
      }
      final PrivilegedExceptionAction<GSSCredential> action =
          new PrivilegedExceptionAction<GSSCredential>() {
            @Override
            public GSSCredential run() throws GSSException {
              return manager.createCredential(
                  null, credentialLifetime, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY);
            }
          };
      gssContext = manager.createContext(Subject.doAs(subject, action));

      outToken = Subject.doAs(lc.getSubject(), new AcceptAction(gssContext, decoded));

      if (outToken == null) {
        if (log.isDebugEnabled()) {
          log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"));
        }
        // Start again
        response.setHeader("WWW-Authenticate", "Negotiate");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
      }

      principal =
          Subject.doAs(
              subject,
              new AuthenticateAction(context.getRealm(), gssContext, storeDelegatedCredential));

    } catch (GSSException e) {
      if (log.isDebugEnabled()) {
        log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"), e);
      }
      response.setHeader("WWW-Authenticate", "Negotiate");
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return false;
    } catch (PrivilegedActionException e) {
      Throwable cause = e.getCause();
      if (cause instanceof GSSException) {
        if (log.isDebugEnabled()) {
          log.debug(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
        }
      } else {
        log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
      }
      response.setHeader("WWW-Authenticate", "Negotiate");
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return false;
    } finally {
      if (gssContext != null) {
        try {
          gssContext.dispose();
        } catch (GSSException e) {
          // Ignore
        }
      }
      if (lc != null) {
        try {
          lc.logout();
        } catch (LoginException e) {
          // Ignore
        }
      }
    }

    // Send response token on success and failure
    response.setHeader("WWW-Authenticate", "Negotiate " + Base64.encodeBase64String(outToken));

    if (principal != null) {
      register(request, response, principal, Constants.SPNEGO_METHOD, principal.getName(), null);

      Pattern p = noKeepAliveUserAgents;
      if (p != null) {
        MessageBytes ua = request.getCoyoteRequest().getMimeHeaders().getValue("user-agent");
        if (ua != null && p.matcher(ua.toString()).matches()) {
          response.setHeader("Connection", "close");
        }
      }
      return true;
    }

    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return false;
  }