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:org.apache.felix.karaf.jaas.modules.properties.PropertiesLoginModule.java

public boolean login() throws LoginException {
    Properties users = new Properties();
    File f = new File(usersFile);
    try {/*w w  w . j  a  v  a  2s  . co m*/
        users.load(new java.io.FileInputStream(f));
    } catch (IOException ioe) {
        throw new LoginException("Unable to load user properties file " + f);
    }

    Callback[] callbacks = new Callback[2];

    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    try {
        callbackHandler.handle(callbacks);
    } catch (IOException ioe) {
        throw new LoginException(ioe.getMessage());
    } catch (UnsupportedCallbackException uce) {
        throw new LoginException(uce.getMessage() + " not available to obtain information from user");
    }
    user = ((NameCallback) callbacks[0]).getName();
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }

    String userInfos = (String) users.get(user);
    if (userInfos == null) {
        throw new FailedLoginException("User does not exist");
    }
    String[] infos = userInfos.split(",");
    if (!new String(tmpPassword).equals(infos[0])) {
        throw new FailedLoginException("Password does not match");
    }

    principals = new HashSet<Principal>();
    principals.add(new UserPrincipal(user));
    for (int i = 1; i < infos.length; i++) {
        principals.add(new RolePrincipal(infos[i]));
    }

    users.clear();

    if (debug) {
        LOG.debug("login " + user);
    }
    return true;
}

From source file:org.alejandria.security.auth.JAASLocalAuthModule.java

@Override
public boolean login() throws LoginException {
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("user");
    callbacks[1] = new PasswordCallback("password", true);

    try {/*w w w  .  jav  a  2 s  . c  o m*/
        this.handler.handle(callbacks);

        String user = ((NameCallback) callbacks[0]).getName();
        String password = String.valueOf(((PasswordCallback) callbacks[1]).getPassword());

        if (user != null && password != null) {
            //manage user and password with database  
            ApplicationContext ctx = ApplicationContextProvider.getSpringApplicationContext();

            userService = ctx.getBean(UsuarioService.class);
            if (userService.authenticateUser(user, password)) {
                subject.getPrincipals().add(new UserPrincipal(user));
                return true;
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new LoginException(ex.getMessage());
    } catch (UnsupportedCallbackException ex) {
        throw new LoginException(ex.getMessage());
    }
    return false;
}

From source file:de.adorsys.oauth.loginmodule.OAuthClientIdLoginModule.java

private boolean validateRequest() throws LoginException {

    HttpServletRequest request = fromPolicyContext(HttpServletRequest.class);
    if (request != null && request.getUserPrincipal() != null) {
        return false;
    }//from w w w .j av a  2s.  c om

    AuthorizationRequest authorizationRequest = fromPolicyContext(AuthorizationRequest.class);
    if (authorizationRequest == null) {
        return false;
    }

    ClientID clientID = authorizationRequest.getClientID();

    String redirectionURIs = System.getProperty("oauth.clients." + clientID + ".redirectionURIs");
    if (redirectionURIs == null) {
        LOG.warn(
                "Unknow OAUTH ClientID {} requested a token. Please define system property 'oauth.clients.{}.redirectionURIs'.",
                clientID, clientID);
        throw new LoginException(
                "Unknow OAUTH ClientID {} requested a token. Please define system property 'oauth.clients.{}.redirectionURIs'.");
    }

    String redirectUri = authorizationRequest.getRedirectionURI().toString();

    for (String allowedUri : Arrays.asList(redirectionURIs.split(","))) {
        if (StringUtils.startsWithIgnoreCase(redirectUri, allowedUri)) {
            return true;
        }
    }

    LOG.warn(
            "OAUTH ClientID {} requested a token but the redirect urls does not match. Actual redirectionurl {} is not defined in {}.",
            clientID, authorizationRequest.getRedirectionURI(), redirectionURIs);
    throw new LoginException(
            "OAUTH ClientID {} requested a token but the redirect urls does not match. Actual redirectionurl {} is not defined in {}.");
}

From source file:org.apache.ranger.authentication.unix.jaas.PamLoginModule.java

private void obtainUserAndPassword() throws LoginException {
    if (_callbackHandler == null) {
        throw new LoginException(
                "Error: no CallbackHandler available  to gather authentication information from the user");
    }/*from   www.  ja v a 2 s  .  c  om*/

    try {
        NameCallback nameCallback = new NameCallback("username");
        PasswordCallback passwordCallback = new PasswordCallback("password", false);

        invokeCallbackHandler(nameCallback, passwordCallback);

        initUserName(nameCallback);
        initPassword(passwordCallback);
    } catch (IOException | UnsupportedCallbackException ex) {
        LoginException le = new LoginException("Error in callbacks");
        le.initCause(ex);
        throw le;
    }
}

From source file:info.magnolia.jaas.sp.jcr.JCRAuthorizationModule.java

/**
 * Update subject with ACL and other properties
 */// w ww .j  a v  a  2s . c o  m
public boolean commit() throws LoginException {
    if (!this.success) {
        throw new LoginException("failed to authenticate " + this.name);
    }
    this.setEntity();
    this.setACL();
    return true;
}

From source file:org.apache.nifi.security.krb.AbstractKerberosUser.java

/**
 * Performs a login using the specified principal and keytab.
 *
 * @throws LoginException if the login fails
 *//*  w  ww . j  a  va2s .com*/
@Override
public synchronized void login() throws LoginException {
    if (isLoggedIn()) {
        return;
    }

    try {
        // If it's the first time ever calling login then we need to initialize a new context
        if (loginContext == null) {
            LOGGER.debug("Initializing new login context...");
            this.subject = new Subject();
            this.loginContext = createLoginContext(subject);
        }

        loginContext.login();
        loggedIn.set(true);
        LOGGER.debug("Successful login for {}", new Object[] { principal });
    } catch (LoginException le) {
        throw new LoginException("Unable to login with " + principal + " due to: " + le.getMessage());
    }
}

From source file:com.cubusmail.server.mail.security.MailboxLoginModule.java

public boolean login() throws LoginException {

    if (this.callbackHandler == null) {
        log.fatal("callbackHandler is null");
        throw new LoginException(IErrorCodes.EXCEPTION_AUTHENTICATION_FAILED);
    }//from  w  ww.  java  2s  . c o  m

    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username");
    callbacks[1] = new PasswordCallback("Password", false);

    try {
        this.callbackHandler.handle(callbacks);
        String username = ((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];
        }
        char[] password = new char[tmpPassword.length];
        System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length);
        ((PasswordCallback) callbacks[1]).clearPassword();

        // start authentication
        // TODO: very dirty, must be replaced by Spring Security stuff
        ApplicationContext context = WebApplicationContextUtils
                .getRequiredWebApplicationContext(SessionManager.getRequest().getSession().getServletContext());
        MailboxFactory factory = context.getBean(MailboxFactory.class);
        IMailbox mailbox = factory.createMailbox(IMailbox.TYPE_IMAP);
        mailbox.init(username, new String(password));

        log.debug("Start login...");
        mailbox.login();
        log.debug("Login successful");

        this.mailboxPrincipal = new MailboxPrincipal(username, mailbox);
        this.succeeded = true;
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        throw new LoginException(ioe.toString());
    } catch (UnsupportedCallbackException uce) {
        log.error(uce.getMessage(), uce);
        throw new LoginException(IErrorCodes.EXCEPTION_AUTHENTICATION_FAILED);
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        mapMessagingException(e);
    }

    return this.succeeded;
}

From source file:com.pymmasoftware.platform.login.loginmodule.DroolsLoginModule.java

@Override
public boolean login() throws LoginException {
    succeeded = false;/*www.  j  a  v  a  2  s.c om*/
    QueryRunner queryRunner = null;
    try {
        userPrincipal = null;
        roles = null;
        if (callbackHandler == null)
            throw new LoginException("No callback handler");

        NameCallback nameCallback = new NameCallback("Username");
        PasswordCallback passwordCallback = new PasswordCallback("Password", false);

        Callback[] callbacks = new Callback[] { nameCallback, passwordCallback };
        try {
            callbackHandler.handle(callbacks);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedCallbackException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        username = nameCallback.getName();
        password = new String(passwordCallback.getPassword());

        queryRunner = new QueryRunner(dataSource);

        // Create a ResultSetHandler implementation to convert the
        // first row into an Object[].
        ResultSetHandler<DroolsPrincipal> h = new ResultSetHandler<DroolsPrincipal>() {
            public DroolsPrincipal handle(ResultSet rs) throws SQLException {
                if (!rs.next()) {
                    return null;
                }

                ResultSetMetaData meta = rs.getMetaData();
                String userName = rs.getString("username");

                DroolsPrincipal droolsPrincipal = new DroolsPrincipal(userName);
                droolsPrincipal.setId(rs.getInt("id"));

                return droolsPrincipal;
            }
        };
        ResultSetHandler<List<String>> hh = new ResultSetHandler<List<String>>() {
            public List<String> handle(ResultSet rs) throws SQLException {
                if (!rs.next()) {
                    return null;
                }
                List<String> droolsGroups = new ArrayList<>();
                boolean goOne = true;
                while (goOne) {
                    String groupName = rs.getString("groups");

                    droolsGroups.add(groupName);
                    if (rs.next() == false) {
                        goOne = false;
                    }
                }
                return droolsGroups;
            }
        };

        String sqlname = "select * from guvnorusers where username = ? and password = ? ";
        DroolsPrincipal user = queryRunner.query(sqlname, h, username, password);
        if (user == null) {
            succeeded = false;
            throw new FailedLoginException("The username or The password is incorrect");
        } else {

            userPrincipal = user;
            String sqlname2 = "select groups from guvnorgroups gr,guvnorusers_groups gr_user "
                    + "where gr.id = gr_user.groups_id  " + "and gr_user.guvnorusers_id= ?";
            List<String> droolsGroups = queryRunner.query(sqlname2, hh, user.getId());
            if (droolsGroups != null) {
                int i = droolsGroups.size();
                roles = new String[i];
                i = 0;
                for (String droolsGroup : droolsGroups) {
                    roles[i] = droolsGroup;
                    i++;
                }
            }
            succeeded = true;
            return true;
        }

    } catch (Exception e) {
        throw new LoginException(e.getMessage());
    } finally {
        queryRunner = null;
    }

}

From source file:info.magnolia.jaas.sp.jcr.JCRAuthenticationModule.java

/**
 * Update subject with ACL and other properties
 *//*from   www  .  j  a  v  a 2s.c  o m*/
public boolean commit() throws LoginException {
    if (!this.success) {
        throw new LoginException("failed to authenticate " + this.name);
    }
    this.setEntity();
    return true;
}

From source file:gov.nih.nci.ncicb.cadsr.common.security.jboss.DBLoginModule.java

public boolean login() throws LoginException {
    try {//from  ww w  .  jav a2s.  c om
        logger.info("In another login");
        if (super.login()) {
            Object username = sharedState.get("javax.security.auth.login.name");
            if (username instanceof Principal) {
                identity = (Principal) username;
            } else {
                String name = username.toString();
                try {
                    identity = createIdentity(name);
                } catch (Exception e) {
                    throw new LoginException("Failed to create principal: " + e.getMessage());
                }
            }
            Object password = sharedState.get("javax.security.auth.login.password");
            if (password instanceof char[]) {
                credential = (char[]) password;
            } else if (password != null) {
                String tmp = password.toString();
                credential = tmp.toCharArray();
            }

            return true;
        }
        super.loginOk = false;
        String[] info = getUsernameAndPassword();
        String username = info[0];
        String password = info[1];
        if ((username == null) && (password == null)) {
            identity = unauthenticatedIdentity;
        }
        if (identity == null) {
            try {
                identity = createIdentity(username);
            } catch (Exception e) {
                throw new LoginException("Failed to create principal: " + e.getMessage());
            }
            String errMsg = userCredential(username.toUpperCase(), password);
            if (!errMsg.equals(""))
                throw new FailedLoginException(errMsg);

            /* since user credential takes care of the authentication, it is not needed
            if (!authenticateUser(username, password)) {
                throw new FailedLoginException("Incorrect username and password");
            } */
        }
        if (getUseFirstPass()) {
            sharedState.put("javax.security.auth.login.name", username);
            sharedState.put("javax.security.auth.login.password", credential);
        }
        super.loginOk = true;
        logger.debug("loginOk=" + loginOk);
    } catch (LoginException le) {
        logger.error("error at login : ", le);
        throw le;
    }
    return true;
}