List of usage examples for javax.security.auth.callback NameCallback NameCallback
public NameCallback(String prompt)
From source file:net.ontopia.topicmaps.nav2.realm.TMLoginModule.java
/** * Prompt the user for username and password, and verify those. *//*from www . ja va 2 s. co m*/ @Override public boolean login() throws LoginException { log.debug("TMLoginModule: login"); if (callbackHandler == null) throw new LoginException( "Error: no CallbackHandler available " + "to garner authentication information from the user"); // prompt for a user name and password NameCallback nameCallback = new NameCallback("user name: "); PasswordCallback passwordCallback = new PasswordCallback("password: ", false); try { callbackHandler.handle(new Callback[] { nameCallback, passwordCallback }); this.username = nameCallback.getName(); char[] charpassword = passwordCallback.getPassword(); password = (charpassword == null ? "" : new String(charpassword)); passwordCallback.clearPassword(); } catch (java.io.IOException ioe) { throw new LoginException(ioe.toString()); } catch (UnsupportedCallbackException uce) { throw new LoginException("Error: " + uce.getCallback() + " not available to garner authentication information " + "from the user"); } // verify the username/password loginSucceeded = verifyUsernamePassword(username, password); return loginSucceeded; }
From source file:info.magnolia.jaas.sp.AbstractLoginModule.java
@Override public boolean login() throws LoginException { if (this.getSkip()) { return true; }/*from ww w . ja v a2 s. c o m*/ if (this.callbackHandler == null) { throw new LoginException("Error: no CallbackHandler available"); } Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("name"); callbacks[1] = new PasswordCallback("pswd", false); // if the realm is not defined in the jaas configuration // we ask use a callback to get the value if (this.useRealmCallback) { callbacks = (Callback[]) ArrayUtils.add(callbacks, new RealmCallback()); } this.success = false; try { this.callbackHandler.handle(callbacks); this.name = ((NameCallback) callbacks[0]).getName(); this.pswd = ((PasswordCallback) callbacks[1]).getPassword(); if (this.useRealmCallback) { String aRealm = ((RealmCallback) callbacks[2]).getRealm(); this.realm = StringUtils.isBlank(aRealm) ? this.realm : Realm.Factory.newRealm(aRealm); } this.validateUser(); } catch (IOException ioe) { log.debug("Exception caught", ioe); throw new LoginException(ioe.toString()); } catch (UnsupportedCallbackException ce) { log.debug(ce.getMessage(), ce); throw new LoginException(ce.getCallback().toString() + " not available"); } // TODO: should not we set success BEFORE calling validateUser to give it chance to decide whether to throw an exception or reset the value to false? this.success = true; this.setSharedStatus(STATUS_SUCCEEDED); return this.success; }
From source file:com.flexive.core.security.FxDefaultLogin.java
/** * Verify the name/password combination. * * @return true always, since this LoginModule should not be ignored. * @throws FailedLoginException if the authentication fails. * @throws LoginException if this LoginModule is unable to perform the authentication. */// w w w . j ava2 s. c o m @Override public boolean login() throws LoginException { LoginException le = null; try { // Determine username and password using the callback handler final Callback[] callbacks = new Callback[] { new NameCallback("user: "), new PasswordCallback("password: ", true), new FxCallback() }; callbackHandler.handle(callbacks); FxCallback ac = ((FxCallback) callbacks[2]); final String username = ((NameCallback) callbacks[0]).getName(); final PasswordCallback pc = (PasswordCallback) callbacks[1]; final String password = new String((pc.getPassword())); pc.clearPassword(); UserTicket ticket = FxAuthenticationHandler.login(username, password, ac); // Set the credentials and principals this.tempPrincipals.add(new FxPrincipal(ticket)); // The login was successfull success = true; if (LOG.isInfoEnabled()) LOG.info("User [" + ticket.getUserName() + "] successfully logged in, ticket=" + ticket); } catch (IOException exc) { le = new FxLoginFailedException("IOException: " + exc.getMessage(), FxLoginFailedException.TYPE_UNKNOWN_ERROR); LOG.error(le); } catch (UnsupportedCallbackException exc) { le = new FxLoginFailedException("IOException: " + exc.getMessage(), FxLoginFailedException.TYPE_UNKNOWN_ERROR); LOG.error(le); } // Log and throw exceptions if (le != null) { success = false; throw le; } return true; }
From source file:com.ideabase.repository.core.auth.RepositoryLoginModule.java
/** * Send callback request for user name and user password.<br> * @return return a string array with index 0 of user name and index 1 * of password.//from w w w . j a v a 2 s . c o m */ private String[] getUserAndPassword() throws IOException, UnsupportedCallbackException { final String[] userInputs = new String[2]; Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback(PROMPT_USER_NAME); callbacks[1] = new PasswordCallback(PROMPT_USER_PASSWORD, ECHO_ON); // send callback request to the authentication request sender mCallbackHandler.handle(callbacks); userInputs[0] = ((NameCallback) callbacks[0]).getName(); userInputs[1] = String.valueOf(((PasswordCallback) callbacks[1]).getPassword()); // clear password callback ((PasswordCallback) callbacks[1]).clearPassword(); // return user name and password. return userInputs; }
From source file:net.java.jaspicoil.SimpleBasicServerAuthModule.java
/** * Authenticate a received service request. * <p/>/* w w w. j av a 2 s .c om*/ * This method is called to transform the mechanism-specific request message * acquired by calling getRequestMessage (on messageInfo) into the validated * application message to be returned to the message processing runtime. If * the received message is a (mechanism-specific) meta-message, the method * implementation must attempt to transform the meta-message into a * corresponding mechanism-specific response message, or to the validated * application request message. The runtime will bind a validated * application message into the the corresponding service invocation. * <p> * This method conveys the outcome of its message processing either by * returning an AuthStatus value or by throwing an AuthException. * <p/> * From a performance point of view this method will be called twice for * each resource with a security constraint on it. Resources with no * security constraint do not result in a call to this method. * * @param messageInfo * A contextual object that encapsulates the client request and * server response objects, and that may be used to save state * across a sequence of calls made to the methods of this * interface for the purpose of completing a secure message * exchange. * @param clientSubject * A Subject that represents the source of the service request. * It is used by the method implementation to store Principals * and credentials validated in the request. * @param serviceSubject * A Subject that represents the recipient of the service * request, or null. It may be used by the method implementation * as the source of Principals or credentials to be used to * validate the request. If the Subject is not null, the method * implementation may add additional Principals or credentials * (pertaining to the recipient of the service request) to the * Subject. * @return An AuthStatus object representing the completion status of the * processing performed by the method. The AuthStatus values that * may be returned by this method are defined as follows: * <p/> * <ul> * <li>AuthStatus.SUCCESS when the application request message was * successfully validated. The validated request message is * available by calling getRequestMessage on messageInfo. * <p/> * <li>AuthStatus.SEND_SUCCESS to indicate that * validation/processing of the request message successfully * produced the secured application response message (in * messageInfo). The secured response message is available by * calling getResponseMessage on messageInfo. * <p/> * <li>AuthStatus.SEND_CONTINUE to indicate that message validation * is incomplete, and that a preliminary response was returned as * the response message in messageInfo. * <p/> * When this status value is returned to challenge an application * request message, the challenged request must be saved by the * authentication module such that it can be recovered when the * module's validateRequest message is called to process the request * returned for the challenge. * <p/> * <li>AuthStatus.SEND_FAILURE to indicate that message validation * failed and that an appropriate failure response message is * available by calling getResponseMessage on messageInfo. * </ul> * @throws AuthException When the message processing failed without * establishing a failure response message (in messageInfo). */ public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { // Get the servlet context final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage(); final HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage(); final String auth = request.getHeader(AUTHORIZATION_HEADER); // Test prefix for HTTP BASIC Auth if (auth != null && StringUtils.startsWithIgnoreCase(auth, "basic ")) { // We might have a valid header, so try to decode it final String data = new String(Base64.decodeBase64(auth.substring(BASIC_PREFIX_LENGTH)), UTF_8); final int splitIndex = data.indexOf(':'); if (splitIndex < 0) { return sendErrorAndAuthenticateRequest(request, response, "Wrong WWW-Authenticate header format"); } final String username = data.substring(splitIndex); final char[] password = data.substring(splitIndex + 1, data.length()).toCharArray(); // Prepare the JAAS callback to feed any LoginModule with user and password final NameCallback nameCallback = new NameCallback("username"); nameCallback.setName(username); final PasswordCallback passwordCallback = new PasswordCallback(getRealm(request), false); passwordCallback.setPassword(password); final CallbackHandler delegatedHandler = new CallbackHandler() { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { final Callback c = callbacks[i]; if (c instanceof NameCallback) { ((NameCallback) c).setName(username); } else if (c instanceof PasswordCallback) { ((PasswordCallback) c).setPassword(password); } else { throw new UnsupportedOperationException( String.format("Callback type %s (%s) is not supported yet.", c.getClass(), c)); } } } }; if (this.jaasContextName == null) { throw new UnsupportedOperationException( "No delegate JAAS context found. As per JASPIC JAAS Bridge profile, this parameter is requiered."); } try { // Create a new JAAS context with the delegated data & try to login final LoginContext context = new LoginContext(this.jaasContextName, delegatedHandler); context.login(); // Get the authenticated subject from the JAAS context Subject authenticatedSubject = context.getSubject(); final PasswordValidationCallback passwordValidationCallback = new PasswordValidationCallback( authenticatedSubject, username, password); // notify JASPIC containerr for the name, password and subject this.handler.handle(new Callback[] { passwordValidationCallback }); } catch (final LoginException ex) { // If there was any issue during the JAAS login, fail the process final AuthException aex = new AuthException( String.format("Fail to login user %s with the delegated JAAS context %s", username, this.jaasContextName)); aex.initCause(ex); } catch (final IOException e) { LOG.log(Level.WARNING, "Unable to call the handlers for name=" + nameCallback, e); } catch (final UnsupportedCallbackException e) { LOG.log(Level.WARNING, "Unable to call the handlers for name=" + nameCallback, e); } } else if (this.mandatory) { return sendErrorAndAuthenticateRequest(request, response, "AuthModule was mandatory but no valid credential was provided"); } else { LOG.info("No authentication was provided bu Basic AuthModule is not mandatory so return SUCCESS."); } return AuthStatus.SUCCESS; }
From source file:gov.nih.nci.security.authentication.loginmodules.CSMLoginModule.java
/** * Retrieves the user credentials from the CallBacks and tries to validate * them against the database. It retrieves userID and password from the * CallbackHandler. It uses helper class to perform the actual authentication * operations and access the user record. This method returns a true if * the user authentication was sucessful else it throws a Login Exception. * @throws LoginException //from ww w.j a va2 s . c om * @see javax.security.auth.spi.LoginModule#login() */ public boolean login() throws LoginException, CSInternalLoginException, CSInternalConfigurationException { if (callbackHandler == null) { if (log.isDebugEnabled()) log.debug("Authentication|||login|Failure| Error in obtaining the CallBack Handler |"); throw new LoginException("Error in obtaining Callback Handler"); } Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("userid: "); callbacks[1] = new PasswordCallback("password: ", false); try { callbackHandler.handle(callbacks); userID = ((NameCallback) callbacks[0]).getName(); char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword(); if (tmpPassword == null) { // treat a NULL password as an empty password tmpPassword = new char[0]; } password = new char[tmpPassword.length]; System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length); ((PasswordCallback) callbacks[1]).clearPassword(); } catch (java.io.IOException e) { if (log.isDebugEnabled()) log.debug("Authentication|||login|Failure| Error in creating the CallBack Handler |" + e.getMessage()); throw new LoginException("Error in Creating the CallBack Handler"); } catch (UnsupportedCallbackException e) { if (log.isDebugEnabled()) log.debug("Authentication|||login|Failure| Error in creating the CallBack Handler |" + e.getMessage()); throw new LoginException("Error in Creating the CallBack Handler"); } if (isFirstTimeLogin(options, userID)) { loginSuccessful = false; password = null; throw new FailedLoginException("User logging in first time, Password should be changed "); } DataConfiguration config; try { config = ConfigurationHelper.getConfiguration(); } catch (CSConfigurationException e) { // TODO Auto-generated catch block throw new CSInternalConfigurationException("Exception while reading config data!!"); } if (isPasswordExpired(options, userID)) { loginSuccessful = false; userID = null; password = null; throw new CredentialExpiredException("User password expired, Ceate new password"); } try { //now validate user if (validate(options, userID, password, subject)) { if (isActive(options, userID)) loginSuccessful = true; else { loginSuccessful = false; password = null; throw new AccountExpiredException("User is not active, Contact the system administrator"); } } else { // clear the values loginSuccessful = false; userID = null; password = null; throw new LoginException("Invalid Login Credentials"); } } catch (FailedLoginException fle) { if (log.isDebugEnabled()) if (log.isDebugEnabled()) log.debug("Authentication|||login|Failure| Invalid Login Credentials |" + fle.getMessage()); throw new LoginException("Invalid Login Credentials"); } if (log.isDebugEnabled()) log.debug("Authentication|||login|Success| Authentication is " + loginSuccessful + "|"); return loginSuccessful; }
From source file:org.jasig.cas.client.jaas.CasLoginModule.java
public boolean login() throws LoginException { log.debug("Performing login."); final NameCallback serviceCallback = new NameCallback("service"); final PasswordCallback ticketCallback = new PasswordCallback("ticket", false); try {/*from w ww .j av a2s. c o m*/ this.callbackHandler.handle(new Callback[] { ticketCallback, serviceCallback }); } catch (final IOException e) { log.info("Login failed due to IO exception in callback handler: " + e); throw (LoginException) new LoginException("IO exception in callback handler: " + e).initCause(e); } catch (final UnsupportedCallbackException e) { log.info("Login failed due to unsupported callback: " + e); throw (LoginException) new LoginException( "Callback handler does not support PasswordCallback and TextInputCallback.").initCause(e); } if (ticketCallback.getPassword() != null) { this.ticket = new TicketCredential(new String(ticketCallback.getPassword())); final String service = CommonUtils.isNotBlank(serviceCallback.getName()) ? serviceCallback.getName() : this.service; if (this.cacheAssertions) { synchronized (ASSERTION_CACHE) { if (ASSERTION_CACHE.get(ticket) != null) { log.debug("Assertion found in cache."); this.assertion = (Assertion) ASSERTION_CACHE.get(ticket); } } } if (this.assertion == null) { log.debug("CAS assertion is null; ticket validation required."); if (CommonUtils.isBlank(service)) { log.info("Login failed because required CAS service parameter not provided."); throw new LoginException( "Neither login module nor callback handler provided required service parameter."); } try { if (log.isDebugEnabled()) { log.debug("Attempting ticket validation with service=" + service + " and ticket=" + ticket); } this.assertion = this.ticketValidator.validate(this.ticket.getTicket(), service); } catch (final Exception e) { log.info("Login failed due to CAS ticket validation failure: " + e); throw (LoginException) new LoginException("CAS ticket validation failed: " + e).initCause(e); } } log.info("Login succeeded."); } else { log.info("Login failed because callback handler did not provide CAS ticket."); throw new LoginException("Callback handler did not provide CAS ticket."); } return true; }
From source file:catalina.realm.JAASMemoryLoginModule.java
/** * Phase 1 of authenticating a <code>Subject</code>. * * @return <code>true</code> if the authentication succeeded, or * <code>false</code> if this <code>LoginModule</code> should be * ignored/*from ww w . j av a 2s . co m*/ * * @exception LoginException if the authentication fails */ public boolean login() throws LoginException { // Set up our CallbackHandler requests if (callbackHandler == null) throw new LoginException("No CallbackHandler specified"); Callback callbacks[] = new Callback[2]; callbacks[0] = new NameCallback("Username: "); callbacks[1] = new PasswordCallback("Password: ", false); // Interact with the user to retrieve the username and password String username = null; String password = null; try { callbackHandler.handle(callbacks); username = ((NameCallback) callbacks[0]).getName(); password = new String(((PasswordCallback) callbacks[1]).getPassword()); } catch (IOException e) { throw new LoginException(e.toString()); } catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); } // Validate the username and password we have received principal = null; // FIXME - look up and check password // Report results based on success or failure if (principal != null) { return (true); } else { throw new FailedLoginException("Username or password is incorrect"); } }
From source file:org.sakaiproject.nakamura.lite.jackrabbit.SparseLoginModule.java
protected String getUserID(Credentials credentials) { String userId = null;/*from www. j a va2 s . c o m*/ if (credentials != null) { if (credentials instanceof GuestCredentials) { userId = anonymousId; } else if (credentials instanceof SimpleCredentials) { userId = ((SimpleCredentials) credentials).getUserID(); } else { try { NameCallback callback = new NameCallback("User-ID: "); callbackHandler.handle(new Callback[] { callback }); userId = callback.getName(); } catch (UnsupportedCallbackException e) { LOGGER.warn("Credentials- or NameCallback must be supported"); } catch (IOException e) { LOGGER.error("Name-Callback failed: " + e.getMessage()); } } } if (userId == null && sharedState.containsKey(KEY_LOGIN_NAME)) { userId = (String) sharedState.get(KEY_LOGIN_NAME); } // still no userId -> anonymousID if its has been defined. // TODO: check again if correct when used with 'extendedAuth' if (userId == null) { userId = anonymousId; } return userId; }
From source file:gov.nih.nci.security.authentication.loginmodules.CSMLoginModule.java
public boolean changePassword(String newPassword) throws LoginException, CSInternalLoginException, CSInternalConfigurationException, CSConfigurationException { if (callbackHandler == null) { if (log.isDebugEnabled()) log.debug("Authentication|||login|Failure| Error in obtaining the CallBack Handler |"); throw new LoginException("Error in obtaining Callback Handler"); }/* w w w . j a v a 2 s . c om*/ Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("userid: "); callbacks[1] = new PasswordCallback("password: ", false); try { callbackHandler.handle(callbacks); userID = ((NameCallback) callbacks[0]).getName(); char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword(); if (tmpPassword == null) { // treat a NULL password as an empty password tmpPassword = new char[0]; } password = new char[tmpPassword.length]; System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length); ((PasswordCallback) callbacks[1]).clearPassword(); } catch (java.io.IOException e) { if (log.isDebugEnabled()) log.debug("Authentication|||login|Failure| Error in creating the CallBack Handler |" + e.getMessage()); throw new LoginException("Error in Creating the CallBack Handler"); } catch (UnsupportedCallbackException e) { if (log.isDebugEnabled()) log.debug("Authentication|||login|Failure| Error in creating the CallBack Handler |" + e.getMessage()); throw new LoginException("Error in Creating the CallBack Handler"); } try { //now validate user if (validate(options, userID, password, subject)) { DataConfiguration config = ConfigurationHelper.getConfiguration(); String encryptedPassword = new String(password); encryptedPassword = StringUtilities.initTrimmedString(encryptPassword(encryptedPassword, "YES")); if (encryptedPassword.equals(encryptPassword(newPassword, "YES"))) { throw new LoginException("The password should be different from the previous passwords"); } if (passwordMatchs(options, userID, newPassword, Integer.parseInt(config.getString("PASSWORD_MATCH_NUM")))) { throw new LoginException("The password should be different from the previous passwords"); } else { changePassword(options, userID, newPassword); if (isFirstTimeLogin(options, userID)) resetFirstTimeLogin(options, userID); insertIntoPasswordHistory(options, userID, password); updatePasswordExpiryDate(options, userID, DateUtils.addDays(Calendar.getInstance().getTime(), Integer.parseInt(config.getString("PASSWORD_EXPIRY_DAYS")))); } } else { // clear the values loginSuccessful = false; userID = null; password = null; throw new FailedLoginException("Invalid Login Credentials"); } } catch (FailedLoginException fle) { if (log.isDebugEnabled()) if (log.isDebugEnabled()) log.debug("Authentication|||login|Failure| Invalid Login Credentials |" + fle.getMessage()); throw new LoginException("Invalid Login Credentials"); } if (log.isDebugEnabled()) log.debug("Authentication|||login|Success| Authentication is " + loginSuccessful + "|"); return loginSuccessful; }