Example usage for javax.security.auth.login LoginException LoginException

List of usage examples for javax.security.auth.login LoginException LoginException

Introduction

In this page you can find the example usage for javax.security.auth.login LoginException LoginException.

Prototype

public LoginException(String msg) 

Source Link

Document

Constructs a LoginException with the specified detail message.

Usage

From source file:edu.vt.middleware.ldap.jaas.AbstractLoginModule.java

/** {@inheritDoc} */
public boolean logout() throws LoginException {
    if (this.logger.isTraceEnabled()) {
        this.logger.trace("Begin logout");
    }/*from w  w  w . ja  v a2 s.  co  m*/
    if (this.subject.isReadOnly()) {
        this.clearState();
        throw new LoginException("Subject is read-only.");
    }

    final Iterator<LdapPrincipal> prinIter = this.subject.getPrincipals(LdapPrincipal.class).iterator();
    while (prinIter.hasNext()) {
        this.subject.getPrincipals().remove(prinIter.next());
    }

    final Iterator<LdapDnPrincipal> dnPrinIter = this.subject.getPrincipals(LdapDnPrincipal.class).iterator();
    while (dnPrinIter.hasNext()) {
        this.subject.getPrincipals().remove(dnPrinIter.next());
    }

    final Iterator<LdapRole> roleIter = this.subject.getPrincipals(LdapRole.class).iterator();
    while (roleIter.hasNext()) {
        this.subject.getPrincipals().remove(roleIter.next());
    }

    final Iterator<LdapGroup> groupIter = this.subject.getPrincipals(LdapGroup.class).iterator();
    while (groupIter.hasNext()) {
        this.subject.getPrincipals().remove(groupIter.next());
    }

    final Iterator<LdapCredential> credIter = this.subject.getPrivateCredentials(LdapCredential.class)
            .iterator();
    while (credIter.hasNext()) {
        this.subject.getPrivateCredentials().remove(credIter.next());
    }

    this.clearState();
    this.loginSuccess = false;
    this.commitSuccess = false;
    return true;
}

From source file:org.nuxeo.ecm.platform.login.test.DummyNuxeoLoginModule.java

public boolean login() throws LoginException {
    loginOk = false;/*from   w w  w.j a  v a2s. c  o  m*/

    identity = getPrincipal();
    if (identity == null) { // auth failed
        throw new LoginException("Authentication Failed");
    }

    if (RestrictedLoginHelper.isRestrictedModeActivated()) {
        if (!identity.isAdministrator()) {
            throw new LoginException("Only Administrators can login when restricted mode is activated");
        }
    }

    loginOk = true;
    log.trace("User '" + identity + "' authenticated");

    return true;
}

From source file:org.polymap.core.runtime.Polymap.java

public void login(String username, String passwd) throws LoginException {
    // init params are not available in services
    initHttpParams = new HashMap();

    String jaasConfigFile = "jaas_config.txt";
    File configFile = new File(getWorkspacePath().toFile(), jaasConfigFile);

    ServicesCallbackHandler.challenge(username, passwd);

    // create secureContext
    try {//from   w w w .jav  a2s  .  c o  m
        secureContext = LoginContextFactory.createContext(SERVICES_LOGIN_CONFIG, configFile.toURI().toURL());
    } catch (MalformedURLException e) {
        throw new RuntimeException("Should never happen.", e);
    }

    // login
    secureContext.login();
    subject = secureContext.getSubject();
    principals = new HashSet(subject.getPrincipals());

    // find user
    for (Principal principal : principals) {
        if (principal instanceof UserPrincipal) {
            user = (UserPrincipal) principal;
            break;
        }
    }
    if (user == null) {
        throw new LoginException("Es wurde kein Nutzer in der Konfiguration gefunden");
    }

    // add roles of user to principals
    log.info("Subject: " + subject);
    Set<AuthorizationModule> authModules = subject.getPrivateCredentials(AuthorizationModule.class);
    if (authModules.size() != 1) {
        throw new RuntimeException("No AuthorizationModule specified.");
    }
    principals.addAll(authModules.iterator().next().rolesOf(subject));

    //        subject.getPrivateCredentials().add( Display.getCurrent() );
    //        subject.getPrivateCredentials().add( SWT.getPlatform() );        

    // allow to access the instance directly via current session (find user for example)
    SessionContext.current().setAttribute("user", user);
}

From source file:org.jboss.datavirt.commons.auth.jboss7.SAMLBearerTokenLoginModule.java

/**
 * @see org.jboss.security.auth.spi.AbstractServerLoginModule#getRoleSets()
 *//*  w w w .  j av a  2 s.  com*/
@Override
protected Group[] getRoleSets() throws LoginException {
    Group[] groups = new Group[1];
    groups[0] = new SimpleGroup("Roles");
    try {
        for (String role : roles) {
            groups[0].addMember(createIdentity(role));
        }
    } catch (Exception e) {
        throw new LoginException("Failed to create group principal: " + e.getMessage());
    }
    return groups;
}

From source file:com.vmware.identity.idm.server.provider.ldap.LdapProvider.java

@Override
public PrincipalId authenticate(PrincipalId principal, String password) throws LoginException {
    ValidateUtil.validateNotNull(principal, "principal");

    IIdmAuthStatRecorder idmAuthStatRecorder = this.createIdmAuthStatRecorderInstance(
            DiagnosticsContextFactory.getCurrentDiagnosticsContext().getTenantName(), ActivityKind.AUTHENTICATE,
            EventLevel.INFO, principal);
    idmAuthStatRecorder.start();/*w  w w. j  av a 2  s.  c om*/

    principal = this.normalizeAliasInPrincipal(principal);
    ILdapConnectionEx connection = null;

    try {
        connection = super.getConnection(getUserDN(principal), password, AuthenticationType.PASSWORD, false);
    } catch (Exception ex) {
        log.error("Failed authentication.", ex);
        throw ((LoginException) new LoginException("Login failed").initCause(ex));
    } finally {
        if (connection != null) {
            connection.close();
        }
    }

    idmAuthStatRecorder.end();

    return principal;
}

From source file:org.nuxeo.ecm.platform.login.NuxeoLoginModule.java

@Override
public Principal createIdentity(String username) throws LoginException {
    log.debug("createIdentity: " + username);
    try {/*from  w w w.  j ava 2 s  .c om*/
        NuxeoPrincipal principal;
        if (manager == null) {
            principal = new NuxeoPrincipalImpl(username);
        } else {
            principal = manager.getPrincipal(username);
            if (principal == null) {
                throw new LoginException(String.format("principal %s does not exist", username));
            }
        }

        String principalId = String.valueOf(random.nextLong());
        principal.setPrincipalId(principalId);
        return principal;
    } catch (LoginException e) {
        log.error("createIdentity failed", e);
        LoginException le = new LoginException("createIdentity failed for user " + username);
        le.initCause(e);
        throw le;
    }
}

From source file:com.fiveamsolutions.nci.commons.authentication.CommonsGridLoginModule.java

/**
 * Method to authenticate a Subject (phase 1). This method obtains the login credentials from the callback handle,
 * which obtains the information from the JNDILoginInitialContex, parses the default Grid Service account and Grid
 * User Identity from the username, authenticates the Grid Service account and password and then stores the Grid
 * User Identity in the Login sharedState.
 * //  www .jav a2 s .c  o m
 * @exception LoginException thrown for callbackHandler errors
 * @return true if successful otherwise false
 */
public boolean login() throws LoginException {
    LOG.debug("In login");

    loginSuccessful = false;

    CallackHandlerRecorder cbhr = new CallackHandlerRecorder(callbackHandler);
    String password = cbhr.getPassword();

    /* NameCallback (within CallbackHandler) contains Grid Service account and Grid User Identity, separated 
     * by gridServicePrincipalSeparator
     * For example, "ejbclient||parnellt" 
     * (gridServicePrincipal="ejbclient" 
     * gridServicePrincipalSeparator="||" 
     * Grid User Identity="parnellt")
     */
    String[] identityArray = StringUtils.split(cbhr.getIdentities(), gridServicePrincipalSeparator);

    if (identityArray.length != 2) {
        throw new LoginException("Invalid java.naming.security.principal in InitialContext for Grid Login");
    }

    //this represents the grid service username/account/principal used to authenticate to JNDI
    String username = identityArray[GRID_AUTHENTICATION_ACCOUNT_INDEX];
    //this represents the actual grid client user to be added to JBoss's password-stack for future
    //authorization checks
    String gridUserIdentity = identityArray[GRID_AUTHORIZATION_ACCOUNT_INDEX];

    LOG.debug("Username = " + username);
    LOG.debug("Grid Identity = " + gridUserIdentity);

    /*
     * Check whether the grid service's credentials to authenticate to the application's JAAS 
     * using JNDI is correct. If so, TRUST that the gridUserIdentity has already been authenticated 
     * and add this principal to the JBoss's password-stack for later login-module(s) to perform 
     * authorization checks
     */
    if (gridServicePrincipal.equals(username) && getDecryptedPassword().equals(password)) {
        // Set the Grid User Identity as the authenticated username
        // The password stacking configuration will user the grid identity to authorize access to EJBs
        state.put(CommonLoginModule.JBOSS_PASSWORD_STACKING_USER_PARAM,
                gridUserIdentity.replaceFirst("^.*?/CN=", "").toLowerCase());
        state.put(CommonLoginModule.JBOSS_PASSWORD_STACKING_PASSWORD_PARAM, password);

        loginSuccessful = true;
        LOG.debug("After setting loginSuccessful to true");
    }

    return loginSuccessful;
}

From source file:org.overlord.commons.auth.jboss7.SAMLBearerTokenLoginModule.java

/**
 * @see org.jboss.security.auth.spi.AbstractServerLoginModule#getRoleSets()
 *//*w w w.  ja va  2 s. c om*/
@Override
protected Group[] getRoleSets() throws LoginException {
    Group[] groups = new Group[1];
    groups[0] = new SimpleGroup("Roles"); //$NON-NLS-1$
    try {
        for (String role : roles) {
            groups[0].addMember(createIdentity(role));
        }
    } catch (Exception e) {
        throw new LoginException(
                Messages.getString("SAMLBearerTokenLoginModule.FailedToCreateGroupPrincipal") + e.getMessage()); //$NON-NLS-1$
    }
    return groups;
}

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/* ww  w  .  j av  a2 s  .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.josso.gl2.agent.jaas.SSOGatewayLoginModule.java

/**
 * Retreives the list of roles associated to current principal
 *///from   w  w  w  .jav a2  s.  c  o  m
protected SSORole[] getRoleSets() throws LoginException {
    try {
        // obtain user roles principals and add it to the subject
        SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager();

        return im.findRolesBySSOSessionId(_currentSSOSessionId);
    } catch (Exception e) {
        // logger.error("Session login failed for Principal : " + _ssoUserPrincipal, e);
        throw new LoginException("Session login failed for Principal : " + _ssoUserPrincipal);
    }

}