Пример #1
0
  private synchronized void serviceLogin() throws AuthLoginException {
    debug.message("New Service Login ...");
    System.setProperty("java.security.krb5.realm", kdcRealm);
    System.setProperty("java.security.krb5.kdc", kdcServer);
    System.setProperty("java.security.auth.login.config", "/dev/null");

    try {
      Configuration config = Configuration.getConfiguration();
      WindowsDesktopSSOConfig wtc = null;
      if (config instanceof WindowsDesktopSSOConfig) {
        wtc = (WindowsDesktopSSOConfig) config;
        wtc.setRefreshConfig("true");
      } else {
        wtc = new WindowsDesktopSSOConfig(config);
      }
      wtc.setPrincipalName(servicePrincipalName);
      wtc.setKeyTab(keyTabFile);
      Configuration.setConfiguration(wtc);

      // perform service authentication using JDK Kerberos module
      LoginContext lc = new LoginContext(WindowsDesktopSSOConfig.defaultAppName);
      lc.login();

      serviceSubject = lc.getSubject();
      debug.message("Service login succeeded.");
    } catch (Exception e) {
      debug.error("Service Login Error: ");
      if (debug.messageEnabled()) {
        debug.message("Stack trace: ", e);
      }
      throw new AuthLoginException(amAuthWindowsDesktopSSO, "serviceAuth", null, e);
    }
  }
Пример #2
0
  private String getEncodedKerberosTicket(boolean spnego) throws Exception {

    System.setProperty("java.security.auth.login.config", "src/test/resources/kerberos.jaas");
    System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true");

    Oid kerberos5Oid = null;
    if (spnego) {
      kerberos5Oid = new Oid("1.3.6.1.5.5.2");
    } else {
      kerberos5Oid = new Oid("1.2.840.113554.1.2.2");
    }

    GSSManager manager = GSSManager.getInstance();
    GSSName serverName =
        manager.createName("*****@*****.**", GSSName.NT_HOSTBASED_SERVICE);

    GSSContext context =
        manager.createContext(
            serverName.canonicalize(kerberos5Oid), kerberos5Oid, null, GSSContext.DEFAULT_LIFETIME);

    context.requestCredDeleg(true);

    final byte[] token = new byte[0];

    String contextName = "alice";
    LoginContext lc = new LoginContext(contextName);
    lc.login();

    byte[] ticket =
        (byte[]) Subject.doAs(lc.getSubject(), new CreateServiceTicketAction(context, token));
    return Base64.encode(ticket);
  }
Пример #3
0
  public static void authenticate(
      PGStream pgStream,
      String host,
      String user,
      String password,
      String jaasApplicationName,
      String kerberosServerName,
      Logger logger)
      throws IOException, SQLException {
    if (logger.logDebug()) logger.debug(" <=BE AuthenticationReqGSS");

    Object result = null;

    if (jaasApplicationName == null) jaasApplicationName = "pgjdbc";
    if (kerberosServerName == null) kerberosServerName = "postgres";

    try {
      LoginContext lc =
          new LoginContext(jaasApplicationName, new GSSCallbackHandler(user, password));
      lc.login();

      Subject sub = lc.getSubject();
      PrivilegedAction action =
          new GssAction(pgStream, host, user, password, kerberosServerName, logger);
      result = Subject.doAs(sub, action);
    } catch (Exception e) {
      throw new PSQLException(GT.tr("GSS Authentication failed"), PSQLState.CONNECTION_FAILURE, e);
    }

    if (result instanceof IOException) throw (IOException) result;
    else if (result instanceof SQLException) throw (SQLException) result;
    else if (result != null)
      throw new PSQLException(
          GT.tr("GSS Authentication failed"), PSQLState.CONNECTION_FAILURE, (Exception) result);
  }
  public Subject krb5PasswordLogin(String password) {
    String loginModuleName = "krb5UsernamePasswordLogin";

    LOG.info(
        "Attempting kerberos authentication of user: "******" using username and password mechanism");

    // Set the domain to realm and the kdc
    // System.setProperty("java.security.krb5.realm", "JTLAN.CO.UK");
    // System.setProperty("java.security.krb5.kdc", "jtserver.jtlan.co.uk");
    // System.setProperty("java.security.krb5.conf",
    // "/home/turnerj/git/servlet-security-filter/KerberosSecurityFilter/src/main/resources/krb5.conf");

    // Form jaasOptions map
    Map<String, String> jaasOptions = new HashMap<String, String>();
    jaasOptions.put("useKeyTab", "false");
    jaasOptions.put("storeKey", "false");
    jaasOptions.put("doNotPrompt", "false");
    jaasOptions.put("refreshKrb5Config", "false");
    jaasOptions.put("clearPass", "true");
    jaasOptions.put("useTicketCache", "false");
    LOG.debug("Dynamic jaas configuration used:" + jaasOptions.toString());

    // Create dynamic jaas config
    DynamicJaasConfiguration contextConfig = new DynamicJaasConfiguration();
    contextConfig.addAppConfigEntry(
        loginModuleName,
        "com.sun.security.auth.module.Krb5LoginModule",
        AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
        jaasOptions);

    try {
      /*
       * Create login context using dynamic config
       * The "krb5UsernamePasswordLogin" needs to correspond to a configuration in the jaas config.
       */
      LoginContext loginCtx =
          new LoginContext(
              loginModuleName,
              null,
              new LoginUsernamePasswordHandler(clientPrincipal, password),
              contextConfig);
      loginCtx.login();
      Subject clientSubject = loginCtx.getSubject();
      String loggedInUser = principalNameFromSubject(clientSubject);
      LOG.info(
          "SUCCESSFUL LOGIN for user: "******" using username and password mechanism.");
      return clientSubject;
    } catch (LoginException le) {
      le.printStackTrace();
      // Failed logins are not an application error so the following line is at info level.
      LOG.info(
          "LOGIN FAILED for user: "******" using username and password mechanism. Reason: "
              + le.toString());
      return null;
    }
  }
 @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();
 }
 private Subject getAuthenticatedSubject(
     final String user, final String password, final X509Certificate[] certificates)
     throws LoginException {
   LoginContext lc =
       new LoginContext(configurationName, new JaasCallbackHandler(user, password, certificates));
   lc.login();
   return lc.getSubject();
 }
 protected HttpServletRequest wrapRequest(HttpServletRequest request, LoginContext lc) {
   Set<Principal> set = lc.getSubject().getPrincipals();
   if (!set.isEmpty()) {
     final Principal principal = set.iterator().next();
     return new HttpServletRequestWrapper(request) {
       @Override
       public Principal getUserPrincipal() {
         return principal;
       }
     };
   }
   return request;
 }
  private boolean validLoginContext() {

    if (loginContext == null) return false;

    Subject subject = loginContext.getSubject();
    if (subject == null) return false;
    Set<KerberosTicket> privateCreds = subject.getPrivateCredentials(KerberosTicket.class);
    if (privateCreds == null || privateCreds.size() == 0) return false;

    Iterator<KerberosTicket> iterator = privateCreds.iterator();
    KerberosTicket ticket = iterator.next();
    return ticket.isCurrent();
  }
Пример #9
0
  @Test
  public void testLoginScreenNameWithScreenName() throws Exception {
    _jaasAuthTypeField.set(null, "screenName");

    LoginContext loginContext = getLoginContext(_user.getScreenName(), _user.getPassword());

    try {
      loginContext.login();
    } catch (Exception e) {
      Assert.fail();
    }

    validateSubject(loginContext.getSubject(), _user.getScreenName());
  }
Пример #10
0
  @Test
  public void testLoginEmailAddressWithLogin() throws Exception {
    _jaasAuthTypeField.set(null, "login");

    LoginContext loginContext = getLoginContext(_user.getEmailAddress(), _user.getPassword());

    try {
      loginContext.login();
    } catch (Exception e) {
      Assert.fail();
    }

    validateSubject(loginContext.getSubject(), _user.getEmailAddress());
  }
  /**
   * Returns true if user was successfully authenticated against Kerberos
   *
   * @param username username without Kerberos realm attached
   * @param password kerberos password
   * @return true if user was successfully authenticated
   */
  public Subject authenticateSubject(String username, String password) throws LoginException {
    String principal = getKerberosPrincipal(username);

    logger.debug("Validating password of principal: " + principal);
    loginContext =
        new LoginContext(
            "does-not-matter",
            null,
            createJaasCallbackHandler(principal, password),
            createJaasConfiguration());

    loginContext.login();
    logger.debug("Principal " + principal + " authenticated succesfully");
    return loginContext.getSubject();
  }
Пример #12
0
  @Test
  public void testLoginUserIdWithUserId() throws Exception {
    _jaasAuthTypeField.set(null, "userId");

    LoginContext loginContext =
        getLoginContext(String.valueOf(_user.getUserId()), _user.getPassword());

    try {
      loginContext.login();
    } catch (Exception e) {
      Assert.fail();
    }

    validateSubject(loginContext.getSubject(), String.valueOf(_user.getUserId()));
  }
  private Subject login() throws AuthenticationException {
    try {
      LoginContext lc =
          new LoginContext(
              KerberosLdapContextSource.class.getSimpleName(), null, null, this.loginConfig);

      lc.login();

      return lc.getSubject();
    } catch (LoginException e) {
      AuthenticationException ae = new AuthenticationException(e.getMessage());
      ae.initCause(e);
      throw ae;
    }
  }
  public Subject krb5KeytabLogin(String keytab) {
    String loginModuleName = "krb5NonInteractiveClientLogin";

    LOG.info("Attempting kerberos login of user: "******" using keytab: " + keytab);
    // Form jaasOptions map
    Map<String, String> jaasOptions = new HashMap<String, String>();
    jaasOptions.put("useKeyTab", "true");
    jaasOptions.put("keyTab", keytab);
    jaasOptions.put("principal", clientPrincipal);
    jaasOptions.put("storeKey", "true"); // Need this to be true for when the server side logs in.
    jaasOptions.put("doNotPrompt", "true");
    jaasOptions.put("refreshKrb5Config", "false");
    jaasOptions.put("clearPass", "true");
    jaasOptions.put("useTicketCache", "false");
    LOG.debug("Dynamic jaas configuration used:" + jaasOptions.toString());

    // Create dynamic jaas config
    DynamicJaasConfiguration contextConfig = new DynamicJaasConfiguration();
    contextConfig.addAppConfigEntry(
        loginModuleName,
        "com.sun.security.auth.module.Krb5LoginModule",
        AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
        jaasOptions);
    try {
      /*
       * The nonInteractiveCallbackHandler should not be needed as the jaas config sets the client to use keytab file and not prompt the user.
       * Therefore this is suitable for system authentication. if the callback handler is used the nonInteractiveCallbackHandler just throws exceptions.
       */
      LoginContext loginCtx =
          new LoginContext(
              loginModuleName, null, new NonInteractiveCallbackHandler(), contextConfig);
      loginCtx.login();
      Subject clientSubject = loginCtx.getSubject();
      String loggedInUser = principalNameFromSubject(clientSubject);
      LOG.info("SUCCESSFUL LOGIN for user: "******" using keytab: " + keytab);
      return clientSubject;
    } catch (LoginException le) {
      LOG.info(
          "LOGIN FAILED for user: "******" using keytab: "
              + keytab
              + " Reason: "
              + le.toString());
      le.printStackTrace();
      return null;
    }
  }
Пример #15
0
  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");
    }
  }
  /**
   * Get the currently logged in user.
   *
   * @return the logged in user
   * @throws IOException if login fails
   */
  public static synchronized UserGroupInformation getLoginUser() throws IOException {
    if (loginUser == null) {
      try {
        Subject subject = new Subject();
        LoginContext login;
        if (isSecurityEnabled()) {
          login = new LoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, subject);
        } else if (useConfiguredFileAuth) {
          login = new LoginContext(HadoopConfiguration.FILE_CONFIG_NAME, subject);
        } else {
          login = new LoginContext(HadoopConfiguration.SIMPLE_CONFIG_NAME, subject);
        }
        login.login();
        loginUser = new UserGroupInformation(subject);
        loginUser.setLogin(login);
        // loginUser.setAuthenticationMethod(isSecurityEnabled() ?
        //                                  AuthenticationMethod.KERBEROS :
        //                                  AuthenticationMethod.SIMPLE);
        AuthenticationMethod authMethod = AuthenticationMethod.SIMPLE;
        if (isSecurityEnabled()) {
          authMethod = AuthenticationMethod.KERBEROS;
        } else if (useConfiguredFileAuth) {
          authMethod = AuthenticationMethod.CONFIGFILE;
        } else {
          authMethod = AuthenticationMethod.SIMPLE;
        }
        loginUser.setAuthenticationMethod(authMethod);

        loginUser = new UserGroupInformation(login.getSubject());
        String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION);
        if (fileLocation != null && isSecurityEnabled()) {
          // load the token storage file and put all of the tokens into the
          // user.
          Credentials cred = Credentials.readTokenStorageFiles(fileLocation, conf);
          for (Token<?> token : cred.getAllTokens()) {
            loginUser.addToken(token);
          }
        }
        loginUser.spawnAutoRenewalThreadForUserCreds();
      } catch (LoginException le) {
        throw new IOException("failure to login", le);
      }
    }
    return loginUser;
  }
Пример #17
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();
  }
Пример #18
0
  private static Subject doLogin(String msg) throws LoginException {
    LoginContext lc = null;
    if (verbose) {
      System.out.println(msg);
    }
    try {
      lc = new LoginContext(msg, new TextCallbackHandler());

      // Attempt authentication
      // You might want to do this in a "for" loop to give
      // user more than one chance to enter correct username/password
      lc.login();

    } catch (LoginException le) {
      throw le;
    }
    return lc.getSubject();
  }
Пример #19
0
  public String login() throws IOException {
    try {
      LoginContext loginContext =
          new LoginContext("InetJaas", new InetCallbackHandler(username, password));
      loginContext.login();
      Subject subject = loginContext.getSubject();
      FacesContext context = FacesContext.getCurrentInstance();
      HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
      session.setAttribute("FILTER_SUBJECT", subject);
      this.setUserrole();

      // WebAuthentication webAuthentication = new WebAuthentication();
      // if (!webAuthentication.login(username, password)) {
      // FacesContext context = FacesContext.getCurrentInstance();
      // String message = MessageBundleHelper.getMessageResourceString(
      // "messages", "userInvalidCredentials", null, context
      // .getExternalContext().getRequestLocale());
      // context.addMessage(null, new FacesMessage(
      // FacesMessage.SEVERITY_ERROR, message, message));
      // return "failure";
      // }
      HttpServletResponse response =
          (HttpServletResponse) context.getExternalContext().getResponse();
      response.sendRedirect(context.getExternalContext().encodeResourceURL("index.jspx"));
      context.responseComplete();
      return "success";

    } catch (LoginException e) {
      FacesContext context = FacesContext.getCurrentInstance();
      String message =
          MessageBundleHelper.getMessageResourceString(
              "messages",
              "userInvalidCredentials",
              null,
              context.getExternalContext().getRequestLocale());
      context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message));
      return "failure";
    } catch (IOException e) {
      logger.log(Level.SEVERE, "Could not redirect!", e);
      throw new RuntimeException(e);
    } finally {
      wipePassword();
    }
  }
Пример #20
0
 public Collection getUserGroups() {
     if (mappedGroups==null) {
         mappedGroups=new ArrayList();
         Collection source_principals=lc.getSubject().getPrincipals();
         Map roleMap = (Map) roleMaps.get(loginContextKey);
         if (roleMap==null) {
             roleMap=new HashMap();
             roleMaps.put(loginContextKey,roleMap);
         }
         switch (((Integer)sourceModes.get(loginContextKey)).intValue()) {
 		case JBOSS:
 			// jboss : user, group of roles, group of callerprincipal 
 		    for (java.util.Iterator it=source_principals.iterator();it.hasNext();) {
 		        java.security.Principal principal = (java.security.Principal)it.next();
 		        if (Group.class.isAssignableFrom(principal.getClass())) {
 		            if (principal.getName().equalsIgnoreCase("Roles")) {
 		                // group of roles
 		                Enumeration enumRoles=((Group)principal).members();
 		                while (enumRoles.hasMoreElements()) {
 		                    Principal role = (Principal)enumRoles.nextElement();
 		                    Object mapped_name = roleMap.get(role.getName());
 		        			mappedGroups.add(mapped_name==null?role.getName():mapped_name);
 		                }
 		            }
 		        } 
 		    }    			
 		break;
 		
 		case TOMCAT:
 		case GLASSFISH:
 		default:
 			// tomcat : list of instances of role class & user class
 		    // TODO : diff�rencier le role de l'identit� (utiliser un parametre RoleClass)
 		    for (java.util.Iterator it=source_principals.iterator();it.hasNext();) {
     			String name=((java.security.Principal)it.next()).getName();
     			Object mapped_name = roleMap.get(name);
     			mappedGroups.add(mapped_name==null?name:mapped_name);
     		}
         }
         
     }
     return mappedGroups;
 }
Пример #21
0
  public static void main(String[] args) {
    if (args.length != 2) {
      System.out.println("Usage: java demo.sas.KerberosServer <ior_file> <password>");
      System.exit(-1);
    }

    // login - with Kerberos
    LoginContext loginContext = null;
    try {
      JaasTxtCalbackHandler cbHandler = new JaasTxtCalbackHandler();
      cbHandler.setMyPassword(args[1].toCharArray());
      loginContext = new LoginContext("KerberosService", cbHandler);
      loginContext.login();
    } catch (LoginException le) {
      System.out.println("Login error: " + le);
      System.exit(1);
    }
    mySubject = loginContext.getSubject();
    myPrincipal = (Principal) mySubject.getPrincipals().iterator().next();
    System.out.println("Found principal " + myPrincipal.getName());

    // run in privileged mode
    final String[] finalArgs = args;
    try {
      Subject.doAs(
          mySubject,
          new PrivilegedAction() {
            public Object run() {
              try {
                // create application
                KerberosServer app = new KerberosServer(finalArgs);
                app.orb.run();
              } catch (Exception e) {
                System.out.println("Error running program: " + e);
              }
              return null;
            }
          });
    } catch (Exception e) {
      System.out.println("Error running privileged: " + e);
    }
  }
Пример #22
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.");
  }
Пример #23
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();
  }
Пример #24
0
  @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();
  }
Пример #25
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);
        }
      }
    }
  }
 /**
  * Get sentry client with authenticated Subject (its security-related attributes(for example,
  * kerberos principal and key)
  *
  * @param clientShortName
  * @param clientKeyTabDir
  * @return client's Subject
  */
 public static Subject getClientSubject(String clientShortName, String clientKeyTabDir) {
   String clientKerberosPrincipal = clientShortName + "@" + REALM;
   File clientKeyTabFile = new File(clientKeyTabDir);
   Subject clientSubject =
       new Subject(
           false,
           Sets.newHashSet(new KerberosPrincipal(clientKerberosPrincipal)),
           new HashSet<Object>(),
           new HashSet<Object>());
   try {
     clientLoginContext =
         new LoginContext(
             "",
             clientSubject,
             null,
             KerberosConfiguration.createClientConfig(clientKerberosPrincipal, clientKeyTabFile));
     clientLoginContext.login();
   } catch (Exception ex) {
     LOGGER.error("Exception: " + ex);
   }
   clientSubject = clientLoginContext.getSubject();
   return clientSubject;
 }
  /**
   * Perform the JAAS login and run the command within a privileged scope.
   *
   * @param privilegedSendMessage the PrivilegedSendMessage
   * @return The result Document
   */
  private Document runPrivileged(final PrivilegedSendMessage privilegedSendMessage) {
    final CallbackHandler handler = new ProvidedAuthCallback(username, password);
    Document result;
    try {
      final LoginContext lc =
          new LoginContext("", null, handler, new KerberosJaasConfiguration(kerberosDebug));
      lc.login();

      result = Subject.doAs(lc.getSubject(), privilegedSendMessage);
    } catch (LoginException e) {
      throw new WinRMRuntimeIOException(
          "Login failure sending message on " + getTargetURL() + " error: " + e.getMessage(),
          privilegedSendMessage.getRequestDocument(),
          null,
          e);
    } catch (PrivilegedActionException e) {
      throw new WinRMRuntimeIOException(
          "Failure sending message on " + getTargetURL() + " error: " + e.getMessage(),
          privilegedSendMessage.getRequestDocument(),
          null,
          e.getException());
    }
    return result;
  }
Пример #28
0
 public UsuarioVo loadUserProfile() {
   Subject subject = null;
   UsuarioVo resultado = null;
   String strIdUsuario = null;
   try {
     subject = context.getSubject();
     if (subject != null) {
       Iterator it = subject.getPrincipals().iterator();
       if (it.hasNext()) {
         strIdUsuario = ((UserIdPrincipal) it.next()).getName();
       }
       if (strIdUsuario != null) {
         AdminSvc svc = new AdminSvcImpl();
         Integer iIdUsuario = Integer.valueOf(strIdUsuario);
         resultado = svc.getUsuario(iIdUsuario);
       }
     }
   } catch (Exception e) {
     error(e.getMessage());
     log("SessionBean: " + e.getMessage());
     e.printStackTrace();
   }
   return resultado;
 }
Пример #29
0
 public static void main(String[] args) throws GeneralSecurityException {
   LoginContext loginContext = new LoginContext("Login", new DialogCallbackHandler());
   loginContext.login();
   System.out.println("User authenticated as: " + loginContext.getSubject());
 }
Пример #30
0
 public OracleUser(LoginContext context) throws LoginException {
   this.context = context;
   context.logout();
   context.login();
   this.subject = context.getSubject();
 }