private void authenticateToKDC( GSSAPICallbackHandler callbackHandler, UserDomainInfo userDomainInfo) throws EngineDirectoryServiceException { try { loginContext = new LoginContext(LOGIN_MODULE_POLICY_NAME, callbackHandler); loginContext.login(); userDomainInfo.setLoginContext(loginContext); if (log.isDebugEnabled()) { log.debug("Successful login for user " + userName); } } catch (LoginException ex) { // JAAS throws login exception due to various reasons. // We check if the login exception matches a case where the user // provided wrong authentication details, or // if there was another error - in case the user provided wrong // authentication details, we will abort the kdc search loginContext = null; KerberosReturnCodeParser parser = new KerberosReturnCodeParser(); AuthenticationResult result = parser.parse(ex.getMessage()); if (result == AuthenticationResult.OTHER || result == null) { // An error our error parser does not recognize log.error("Error from Kerberos: " + ex.getMessage()); } else { StringBuilder error = new StringBuilder(); error.append(result.getDetailedMessage()); log.error(error.toString()); } throw new EngineDirectoryServiceException(result); } }
/** * Tries to login the user. If username as well as password are correctly spelled this method * returns the PatientSearch-Site, if not the Login-Failed Site will be returned. * * @return correct login: PatientSearch, else LoginFailed * @throws Exception */ public String login() throws Exception { // FacesContext fc = FacesContext.getCurrentInstance().getExternalContext().getResponse(); // HttpServletResponse resp = // (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse(); // resp. // fc.getMessages(). // throw new Exception(); // TODO: facesContext - register new Error try { LoginContext lc = new LoginContext("Test"); lc.login(); } catch (LoginException e) { e.printStackTrace(); } finally { return "/errorPage.xhtml"; } // File f = null; // f.getName(); // if(findUser(username, password)){ // return "loginAccepted"; // } // else{ // return "loginDenied"; // } // if(findUser(username, password)){ // return "/patientSearch.xhtml"; // } // else{ // return "/loginFalse.xhtml"; // } }
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; } }
/** * Returns true if user with given username exists in kerberos database * * @param username username without Kerberos realm attached or with correct realm attached * @return true if user available */ public boolean isUserAvailable(String username) { logger.debug("Checking existence of user: "******"does-not-matter", null, createJaasCallbackHandler(principal, "fake-password-which-nobody-has"), createJaasConfiguration()); loginContext.login(); throw new IllegalStateException("Didn't expect to end here"); } catch (LoginException le) { String message = le.getMessage(); logger.debug("Message from kerberos: " + message); checkKerberosServerAvailable(le); // Bit cumbersome, but seems to work with tested kerberos servers boolean exists = (!message.contains("Client not found")); return exists; } }
public void authenticate() throws FailedLoginException { mappedGroups=null; contextLoop : for (Iterator it=this.mappedLoginContextNames.keySet().iterator(); it.hasNext();) { loginContextKey = it.next(); try { lc = new LoginContext(mappedLoginContextNames.get(loginContextKey).toString(), new CallbackHandler() { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { Callback[] mono=new Callback[1]; for (int i = 0; i < callbacks.length; i++) { mono[0]=callbacks[i]; if (mono[0] instanceof NameCallback) { ((NameCallback)mono[0]).setName(getUsername()); } else if (mono[0] instanceof PasswordCallback) { ((PasswordCallback)mono[0]).setPassword(getPassword()); } else { getCallbackHandler().handle(mono); } } } }); lc.login(); break contextLoop; } catch (LoginException e) { if (!it.hasNext()) throw new FailedLoginException("mapped LoginContext exception : "+e.getMessage()); } } }
/* * There are several cases this test fails: * * 1. The random selected port is used by another process. No good way to * prevent this happening, coz krb5.conf must be written before KDC starts. * There are two different outcomes: * * a. Cannot start the KDC. A BindException thrown. * b. When trying to access a non-existing KDC, a response is received! * Most likely a Asn1Exception thrown * * 2. Even if a KDC is started, and more than 20 seconds pass by, a timeout * can still happens for the first UDP request. In fact, the KDC did not * received it at all. This happens on almost all platforms, especially * solaris-i586 and solaris-x64. * * To avoid them: * * 1. Catch those exceptions and ignore * * 2. a. Make the timeout longer? useless * b. Read the output carefully, if there is a timeout, it's OK. * Just make sure the retries times and KDCs are correct. * This is tough. * c. Feed the KDC a UDP packet first. The current "solution". */ public static void go(String... expected) throws Exception { try { go0(expected); } catch (BindException be) { System.out.println("The random port is used by another process"); } catch (LoginException le) { Throwable cause = le.getCause(); if (cause instanceof Asn1Exception) { System.out.println("Bad packet possibly from another process"); return; } throw le; } }
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; } }
/** @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")); }
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; } }
private static void testPerformAs() { try { // performAs("service/[email protected]", // "/apps/workgroup-audit/keytab/keytab.workgroup-audit", new Dummy("phoebe")); // performAs("service/[email protected]", "/etc/krb5.keytab", new // DummyAction("phoebe")); // performAs("ldap/[email protected]", "/etc/krb5.keytab", new SearchAction()); performAs("ldap/[email protected]", "/etc/krb5.keytab", new SearchAction()); } catch (LoginException le) { le.printStackTrace(); } catch (PrivilegedActionException pae) { Exception e = pae.getException(); System.out.println("exception msg is: " + e.getMessage()); e.printStackTrace(); } }
/** * Log a user into the site and create the user's session. * * @param username User's login name. * @param password User's unencrypted password. * @param request HttpServletRequest for this action. * @param response HttpServletResponse for this action. * @return Any action error messages that may have occurred. */ private User loginUser( String username, String password, HttpServletRequest request, HttpServletResponse response, ActionErrors e) { User user = null; try { user = UserManager.loginUser(username, password); } catch (LoginException ex) { e.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(ex.getMessage())); } return user; }
/** Call the login method on the Jaas Login Module */ public boolean login() { try { context.login(); // load the user profile and save it in a User object and keep this object in the session usuarioLogged = loadUserProfile(); return true; } catch (FailedLoginException fle) { error(fle.getMessage()); return false; } catch (LoginException le) { error(le.getMessage()); return false; } catch (Exception e) { log("SessionBean1::Exception occured while logging in" + e.getMessage()); error("Error Loggin In"); return false; } }
public boolean initLoginContext(String username, String password) { try { // Create a new instace of the callback handler to be passed to the context CallbackHandler cbh = new SipCallbackHandler(username, password); context = new LoginContext(login_config, cbh); log("SessionBean1::Login context created successfully"); return true; } catch (LoginException le) { error("LoginException: " + le.getMessage()); return false; } catch (Exception e) { error( "Error Creating LoginContext, \n Please make sure your application has been configured properly."); log("SessionBean1::Exception Occured:" + e.getMessage()); return false; } }
public void shutdown() { for (ClientEndpoint endpoint : endpoints.values()) { try { endpoint.destroy(); } catch (LoginException e) { logger.finest(e.getMessage()); } try { final Connection conn = endpoint.getConnection(); if (conn.live()) { conn.close(); } } catch (Exception e) { logger.finest(e); } } endpoints.clear(); }
private void doAuthentication(String user, String password, IDMRealm realm) throws LoginException { try { IUserFacadeRemote userFacadeRemote = realm.locateUserFacade(); boolean valid = userFacadeRemote.isUsernamePasswordValid(user, password); if (!valid) { throw new LoginException("Blad logowania uzytkownika: " + user); } } catch (NamingException ex) { LOGGER.log( Level.SEVERE, "Error checking user name and password: {0} info: {1}", new Object[] {user, ex.getMessage()}); LoginException le = new LoginException("Blad wyszukiwania JNDI."); le.initCause(ex); throw le; } }
@Override public void shutdown(boolean terminate) { for (ClientEndpoint ce : endpointManager.getEndpoints()) { ClientEndpointImpl endpoint = (ClientEndpointImpl) ce; try { endpoint.destroy(); } catch (LoginException e) { logger.finest(e.getMessage()); } try { final Connection conn = endpoint.getConnection(); if (conn.isAlive()) { conn.close("Shutdown of ClientEngine", null); } } catch (Exception e) { logger.finest(e); } } endpointManager.clear(); ownershipMappings.clear(); }
@Override public boolean login() throws LoginException { Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback(Messages.PROMPT_USERNAME.getText()); callbacks[1] = new PasswordCallback(Messages.PROMPT_PASSWORD.getText(), false); try { mCallback.handle(callbacks); } catch (UnsupportedCallbackException e) { final LoginException ex = new FailedLoginException(e.getMessage()); ex.initCause(e); throw ex; } catch (IOException e) { final LoginException ex = new FailedLoginException(e.getMessage()); ex.initCause(e); throw ex; } mUsername = ((NameCallback) callbacks[0]).getName(); if (mUsername == null || mUsername.trim().length() == 0) { throw new AccountNotFoundException(Messages.EMPTY_USERNAME.getText()); } char[] password = ((PasswordCallback) callbacks[1]).getPassword(); try { if (!ClientLoginHelper.isValidCredentials(mUsername, password)) { Messages.USER_LOGIN_ERROR_LOG.warn(this, mUsername); throw new FailedLoginException(Messages.USER_LOGIN_FAIL.getText(mUsername)); } } catch (ClientInitException e) { Messages.USER_LOGIN_ERROR_LOG.warn(this, e, mUsername); LoginException exception = new FailedLoginException(Messages.USER_LOGIN_ERROR.getText()); exception.initCause(e); throw exception; } SLF4JLoggerProxy.debug(this, "login done for user {}", mUsername); // $NON-NLS-1$ return true; }
@Override protected List<ConnectorError> validateValues() { final List<ConnectorError> errors = new ArrayList<ConnectorError>(); testEmptyVar(sugarSoapPort, "sugarSoapPort", errors); testEmptyVar(applicationName, "applicationName", errors); testEmptyVar(user, "user", errors); testEmptyVar(module, "module", errors); try { this.initSugarCrmSoapClient(sugarSoapPort, user, password, applicationName); } catch (MalformedURLException e) { errors.add( new ConnectorError( "sugarSoapPort", new MalformedURLException("URL not valid! " + e.getMessage()))); } catch (LoginException e) { errors.add( new ConnectorError( "user", new LoginException("Wrong user or password! " + e.getMessage()))); } catch (RemoteException e) { errors.add( new ConnectorError( "sugarSoapPort", new RemoteException("Error accessing Sugar services! " + e.getMessage()))); } catch (ServiceException e) { errors.add( new ConnectorError( "sugarSoapPort", new ServiceException("Error accessing Sugar services! " + e.getMessage()))); } catch (Exception e) { errors.add( new ConnectorError( "sugarSoapPort", new Exception("Exception occurred! " + e.getMessage()))); } return errors; }
/** * 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; }
void handleJoinRequest(JoinRequest joinRequest) { final long now = Clock.currentTimeMillis(); String msg = "Handling join from " + joinRequest.address + ", inProgress: " + joinInProgress + (timeToStartJoin > 0 ? ", timeToStart: " + (timeToStartJoin - now) : ""); logger.log(Level.FINEST, msg); boolean validJoinRequest; try { validJoinRequest = node.validateJoinRequest(joinRequest); } catch (Exception e) { validJoinRequest = false; } final Connection conn = joinRequest.getConnection(); if (validJoinRequest) { final MemberImpl member = getMember(joinRequest.address); if (member != null) { if (joinRequest.getUuid().equals(member.getUuid())) { String message = "Ignoring join request, member already exists.. => " + joinRequest; logger.log(Level.FINEST, message); // send members update back to node trying to join again... final long clusterTime = node.getClusterImpl().getClusterTime(); sendProcessableTo(new MembersUpdateCall(lsMembers, clusterTime), conn); sendProcessableTo(new SyncProcess(), conn); return; } // If this node is master then remove old member and process join request. // If requesting address is equal to master node's address, that means master node // somehow disconnected and wants to join back. // So drop old member and process join request if this node becomes master. if (isMaster() || member.getAddress().equals(getMasterAddress())) { logger.log( Level.WARNING, "New join request has been received from an existing endpoint! => " + member + " Removing old member and processing join request..."); // If existing connection of endpoint is different from current connection // destroy it, otherwise keep it. // final Connection existingConnection = // node.connectionManager.getConnection(joinRequest.address); // final boolean destroyExistingConnection = existingConnection != // conn; doRemoveAddress(member.getAddress(), false); } } if (!node.getConfig().getNetworkConfig().getJoin().getMulticastConfig().isEnabled()) { if (node.isActive() && node.joined() && node.getMasterAddress() != null && !isMaster()) { sendProcessableTo(new Master(node.getMasterAddress()), conn); } } if (isMaster() && node.joined() && node.isActive()) { final MemberInfo newMemberInfo = new MemberInfo(joinRequest.address, joinRequest.nodeType, joinRequest.getUuid()); if (node.securityContext != null && !setJoins.contains(newMemberInfo)) { final ILogger securityLogger = node.loggingService.getLogger("com.hazelcast.security"); final Credentials cr = joinRequest.getCredentials(); if (cr == null) { securityLogger.log( Level.SEVERE, "Expecting security credentials " + "but credentials could not be found in JoinRequest!"); sendAuthFail(conn); return; } else { try { LoginContext lc = node.securityContext.createMemberLoginContext(cr); lc.login(); } catch (LoginException e) { securityLogger.log( Level.SEVERE, "Authentication has failed for " + cr.getPrincipal() + '@' + cr.getEndpoint() + " => (" + e.getMessage() + ")"); securityLogger.log(Level.FINEST, e.getMessage(), e); sendAuthFail(conn); return; } } } if (joinRequest.to != null && !joinRequest.to.equals(thisAddress)) { sendProcessableTo(new Master(node.getMasterAddress()), conn); return; } if (!joinInProgress) { if (firstJoinRequest != 0 && now - firstJoinRequest >= MAX_WAIT_SECONDS_BEFORE_JOIN * 1000) { startJoin(); } else { if (setJoins.add(newMemberInfo)) { sendProcessableTo(new Master(node.getMasterAddress()), conn); if (firstJoinRequest == 0) { firstJoinRequest = now; } if (now - firstJoinRequest < MAX_WAIT_SECONDS_BEFORE_JOIN * 1000) { timeToStartJoin = now + WAIT_MILLIS_BEFORE_JOIN; } } if (now > timeToStartJoin) { startJoin(); } } } } } else { conn.close(); } }
protected void checkKerberosServerAvailable(LoginException le) { if (le.getMessage().contains("Port Unreachable")) { throw new ModelException("Kerberos unreachable", le); } }
/** * Get the expected password for the current username available via the getUsername() method. This * is called from within the login() method after the CallbackHandler has returned the username * and candidate password. * * @return the valid password String */ @Override protected String getUsersPassword() throws LoginException { boolean trace = log.isTraceEnabled(); String username = getUsername(); String password = null; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; Transaction tx = null; if (suspendResume) { tx = TransactionDemarcationSupport.suspendAnyTransaction(); if (trace) log.trace("suspendAnyTransaction"); } try { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(dsJndiName); conn = ds.getConnection(); // Get the password if (trace) log.trace("Excuting query: " + principalsQuery + ", with username: "******"Query returned no matches from db"); throw new FailedLoginException("No matching username found in Principals"); } password = rs.getString(1); password = convertRawPassword(password); if (trace) log.trace("Obtained user password"); } catch (NamingException ex) { LoginException le = new LoginException("Error looking up DataSource from: " + dsJndiName); le.initCause(ex); throw le; } catch (SQLException ex) { LoginException le = new LoginException("Query failed"); le.initCause(ex); throw le; } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { } } if (ps != null) { try { ps.close(); } catch (SQLException e) { } } if (conn != null) { try { conn.close(); } catch (SQLException ex) { } } if (suspendResume) { TransactionDemarcationSupport.resumeAnyTransaction(tx); if (log.isTraceEnabled()) log.trace("resumeAnyTransaction"); } } return password; }
/** * Begin user authentication. * * <p>Acquire the user's credentials and verify them against the specified LDAP directory. * * @return true always, since this <code>LoginModule</code> should not be ignored. * @exception FailedLoginException if the authentication fails. * @exception LoginException if this <code>LoginModule</code> is unable to perform the * authentication. */ public boolean login() throws LoginException { if (userProvider == null) { throw new LoginException("Unable to locate the LDAP directory service"); } if (debug) { System.out.println("\t\t[LdapLoginModule] user provider: " + userProvider); } // attempt the authentication if (tryFirstPass) { try { // attempt the authentication by getting the // username and password from shared state attemptAuthentication(true); // authentication succeeded succeeded = true; if (debug) { System.out.println("\t\t[LdapLoginModule] " + "tryFirstPass succeeded"); } return true; } catch (LoginException le) { // authentication failed -- try again below by prompting cleanState(); if (debug) { System.out.println("\t\t[LdapLoginModule] " + "tryFirstPass failed: " + le.toString()); } } } else if (useFirstPass) { try { // attempt the authentication by getting the // username and password from shared state attemptAuthentication(true); // authentication succeeded succeeded = true; if (debug) { System.out.println("\t\t[LdapLoginModule] " + "useFirstPass succeeded"); } return true; } catch (LoginException le) { // authentication failed cleanState(); if (debug) { System.out.println("\t\t[LdapLoginModule] " + "useFirstPass failed"); } throw le; } } // attempt the authentication by prompting for the username and pwd try { attemptAuthentication(false); // authentication succeeded succeeded = true; if (debug) { System.out.println("\t\t[LdapLoginModule] " + "authentication succeeded"); } return true; } catch (LoginException le) { cleanState(); if (debug) { System.out.println("\t\t[LdapLoginModule] " + "authentication failed"); } throw le; } }
@Override protected void startToolL(final IProgressMonitor monitor) throws CoreException { fRjsId = RjsComConfig.registerClientComHandler(fRjs); fRjs.initClient(getTool(), this, fRjsProperties, fRjsId); try { final Map<String, Object> data = new HashMap<String, Object>(); final IToolEventHandler loginHandler = getEventHandler(IToolEventHandler.LOGIN_REQUEST_EVENT_ID); String msg = null; boolean connected = false; while (!connected) { final Map<String, Object> initData = getInitData(); final ServerLogin login = fRjsConnection.getServer().createLogin(Server.C_CONSOLE_CONNECT); try { final Callback[] callbacks = login.getCallbacks(); if (callbacks != null) { final List<Callback> checked = new ArrayList<Callback>(); FxCallback fx = null; for (final Callback callback : callbacks) { if (callback instanceof FxCallback) { fx = (FxCallback) callback; } else { checked.add(callback); } } if (initData != null) { data.putAll(initData); } data.put( LOGIN_ADDRESS_DATA_KEY, (fx != null) ? fAddress.getHost() : fAddress.getAddress()); data.put(LOGIN_MESSAGE_DATA_KEY, msg); data.put(LOGIN_CALLBACKS_DATA_KEY, checked.toArray(new Callback[checked.size()])); if (loginHandler == null) { throw new CoreException( new Status( IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "Login requested but not supported by this configuration.", null)); } if (!loginHandler .handle(IToolEventHandler.LOGIN_REQUEST_EVENT_ID, this, data, monitor) .isOK()) { throw new CoreException(Status.CANCEL_STATUS); } if (fx != null) { RjsUtil.handleFxCallback( RjsUtil.getSession(data, new SubProgressMonitor(monitor, 1)), fx, new SubProgressMonitor(monitor, 1)); } } msg = null; if (monitor.isCanceled()) { throw new CoreException(Status.CANCEL_STATUS); } final Map<String, Object> args = new HashMap<String, Object>(); args.putAll(fRjsProperties); ConsoleEngine rjServer; if (fStartup) { args.put("args", fRArgs); // $NON-NLS-1$ rjServer = (ConsoleEngine) fRjsConnection .getServer() .execute(Server.C_CONSOLE_START, args, login.createAnswer()); } else { rjServer = (ConsoleEngine) fRjsConnection .getServer() .execute(Server.C_CONSOLE_CONNECT, args, login.createAnswer()); } fRjs.setServer(rjServer, 0); connected = true; if (callbacks != null) { loginHandler.handle(IToolEventHandler.LOGIN_OK_EVENT_ID, this, data, monitor); if (initData != null) { initData.put(LOGIN_USERNAME_DATA_KEY, data.get(LOGIN_USERNAME_DATA_KEY)); } } } catch (final LoginException e) { msg = e.getLocalizedMessage(); } finally { if (login != null) { login.clearData(); } } } final ServerInfo info = fRjsConnection.getServer().getInfo(); if (fWorkspaceData.isRemote()) { try { final String wd = FileUtil.toString(fWorkspaceData.toFileStore(info.getDirectory())); if (wd != null) { setStartupWD(wd); } } catch (final CoreException e) { } } else { setStartupWD(info.getDirectory()); } final long timestamp = info.getTimestamp(); if (timestamp != 0) { setStartupTimestamp(timestamp); } final List<IStatus> warnings = new ArrayList<IStatus>(); initTracks(info.getDirectory(), monitor, warnings); if (fStartup && !fStartupsRunnables.isEmpty()) { fQueue.add(fStartupsRunnables.toArray(new IToolRunnable[fStartupsRunnables.size()])); fStartupsRunnables.clear(); } if (!fStartup) { handleStatus( new Status( IStatus.INFO, RConsoleCorePlugin.PLUGIN_ID, addTimestampToMessage( RNicoMessages.R_Info_Reconnected_message, fProcess.getConnectionTimestamp())), monitor); } // fRjs.runMainLoop(null, null, monitor); must not wait at server side fRjs.activateConsole(); scheduleControllerRunnable( new ControllerSystemRunnable( "r/rj/start2", "Finish Initialization / Read Output") { // $NON-NLS-1$ @Override public void run(final IToolService s, final IProgressMonitor monitor) throws CoreException { if (!fRjs.isConsoleReady()) { // R is still working fRjs.runMainLoop(null, null, monitor); } for (final IStatus status : warnings) { handleStatus(status, monitor); } } }); } catch (final RemoteException e) { throw new CoreException( new Status( IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "The R engine could not be started.", e)); } catch (final RjException e) { throw new CoreException( new Status( IStatus.ERROR, RConsoleCorePlugin.PLUGIN_ID, ICommonStatusConstants.LAUNCHING, "An error occured when creating login data.", e)); } }
/** * The instance method checks if for the given user the password is correct. The test itself is * done with * * @param _name name of the person name to check * @param _passwd password of the person to check * @see #checkLogin */ protected boolean checkLogin(final String _name, final String _passwd) { boolean ret = false; try { LoginContext login = new LoginContext(this.application, new LoginCallBackHandler(_name, _passwd)); login.login(); Person person = null; for (JAASSystem system : JAASSystem.getAllJAASSystems()) { Set users = login.getSubject().getPrincipals(system.getPersonJAASPrincipleClass()); System.out.println("---------------------->users=" + users); for (Object persObj : users) { try { String persKey = (String) system.getPersonMethodKey().invoke(persObj, null); Person foundPerson = Person.getWithJAASKey(system, persKey); if (foundPerson == null) { // TODO: JAASKey for person must be added!!! } else if (person == null) { person = foundPerson; } else if (person.getId() != foundPerson.getId()) { LOG.error( "For JAAS system " + system.getName() + " " + "person with key '" + persKey + "' is not unique!" + "Have found person '" + person.getName() + "' " + "(id = " + person.getId() + ") and person " + "'" + foundPerson.getName() + "' " + "(id = " + foundPerson.getId() + ")."); // TODO: throw exception!! } } catch (IllegalAccessException e) { LOG.error("could not execute person key method for system " + system.getName(), e); // TODO: throw exception!! } catch (IllegalArgumentException e) { LOG.error("could not execute person key method for system " + system.getName(), e); // TODO: throw exception!! } catch (InvocationTargetException e) { LOG.error("could not execute person key method for system " + system.getName(), e); // TODO: throw exception!! } } } if (person == null) { for (JAASSystem system : JAASSystem.getAllJAASSystems()) { Set users = login.getSubject().getPrincipals(system.getPersonJAASPrincipleClass()); for (Object persObj : users) { try { String persKey = (String) system.getPersonMethodKey().invoke(persObj, null); if (person == null) { person = Person.createPerson(system, persKey, persKey); } else { person.assignToJAASSystem(system, persKey); } } catch (IllegalAccessException e) { LOG.error("could not execute person key method for system " + system.getName(), e); // TODO: throw exception!! } catch (IllegalArgumentException e) { LOG.error("could not execute person key method for system " + system.getName(), e); // TODO: throw exception!! } catch (InvocationTargetException e) { LOG.error("could not execute person key method for system " + system.getName(), e); // TODO: throw exception!! } } } } person.cleanUp(); for (JAASSystem system : JAASSystem.getAllJAASSystems()) { if (system.getRoleJAASPrincipleClass() != null) { Set rolesJaas = login.getSubject().getPrincipals(system.getRoleJAASPrincipleClass()); Set<Role> rolesEfaps = new HashSet<Role>(); for (Object roleObj : rolesJaas) { try { String roleKey = (String) system.getRoleMethodKey().invoke(roleObj, null); Role roleEfaps = Role.getWithJAASKey(system, roleKey); if (roleEfaps != null) { rolesEfaps.add(roleEfaps); } } catch (IllegalAccessException e) { LOG.error("could not execute role key method for system " + system.getName(), e); } catch (IllegalArgumentException e) { LOG.error("could not execute role key method for system " + system.getName(), e); } catch (InvocationTargetException e) { LOG.error("could not execute role key method for system " + system.getName(), e); } } person.setRoles(system, rolesEfaps); } } ret = true; } catch (EFapsException e) { e.printStackTrace(); LOG.error("login failed for '" + _name + "'", e); } catch (LoginException e) { e.printStackTrace(); LOG.error("login failed for '" + _name + "'", e); } return ret; }