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

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

Introduction

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

Prototype

public FailedLoginException(String msg) 

Source Link

Document

Constructs a FailedLoginException with the specified detail message.

Usage

From source file:com.echounion.portal.util.MyQueryDatabaseAuthenticationHandler.java

@Override
protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws GeneralSecurityException, PreventedException {
    final String username = credential.getUsername();
    final ShiroKit shiroKit = (ShiroKit) this.getPasswordEncoder();
    shiroKit.setSalt(username);/*from ww  w. j av a2s . c  om*/
    final String encryptedPassword = shiroKit.encode(credential.getPassword());

    try {
        final String e = (String) this.getJdbcTemplate().queryForObject(this.sql, String.class,
                new Object[] { username });
        if (!e.equals(encryptedPassword)) {
            throw new FailedLoginException("Password does not match value on record.");
        }
    } catch (final IncorrectResultSizeDataAccessException var5) {
        if (var5.getActualSize() == 0) {
            throw new AccountNotFoundException(username + " not found with SQL query");
        }

        throw new FailedLoginException("Multiple records found for " + username);
    } catch (final DataAccessException var6) {
        throw new PreventedException("SQL exception while executing query for " + username, var6);
    }

    return this.createHandlerResult(credential, this.principalFactory.createPrincipal(username), (List) null);
}

From source file:com.amalto.core.server.security.jaas.DefaultLoginModule.java

@Override
protected void doLogin() throws Exception {
    if (!passwordByUserMap.containsKey(username)) {
        throw new FailedLoginException("Invalid username"); //$NON-NLS-1$
    }//from  w  w w  .  j a  v a 2s  . co  m
    String savedPassword = passwordByUserMap.get(username);
    if (password == null || !password.equals(savedPassword)) {
        throw new FailedLoginException("Invalid password"); //$NON-NLS-1$
    }
}

From source file:com.hs.mail.security.login.PropertiesLoginModule.java

@Override
protected Principal[] validate(Callback[] callbacks) throws LoginException {
    String username = ((NameCallback) callbacks[0]).getName();
    char[] password = ((PasswordCallback) callbacks[1]).getPassword();

    String entry = getLine(file, username + "=");
    if (entry == null)
        throw new AccountNotFoundException("Account for " + username + " not found");
    int index = entry.indexOf('=');
    if (index == -1)
        throw new FailedLoginException("Invalid user record");
    entry = entry.substring(index + 1);/*from   w  ww.j a  v  a2  s  .co  m*/
    index = entry.indexOf(':');
    if (index == -1)
        throw new FailedLoginException("Invalid user record");
    String encodedPwd = entry.substring(0, index);
    String roles = entry.substring(index + 1);
    StringTokenizer st = new StringTokenizer(roles, ",");
    Principal[] principals = new Principal[st.countTokens() + 1];
    for (int i = 0; i < principals.length - 1; i++) {
        principals[i] = new RolePrincipal(st.nextToken().trim());
    }
    principals[principals.length - 1] = new UserPrincipal(username);
    boolean ok = checkPassword(encodedPwd, password);
    if (!ok)
        throw new CredentialException("Incorrect password for " + username);
    else
        return principals;
}

From source file:io.wicket.cas.BCryptSearchModeSearchDatabaseAuthenticationHandler.java

/**
 * {@inheritDoc}/*  www  . ja  v  a  2s. c  o m*/
 */
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
        throws PreventedException, FailedLoginException {

    final String username = credential.getUsername();
    final String password = credential.getPassword();
    final Map<String, Object> userDetails;

    try {
        if (fieldUserAlt.isEmpty()) {
            userDetails = getJdbcTemplate().queryForMap(this.sql, username);
        } else {
            userDetails = getJdbcTemplate().queryForMap(this.sql, username, username);
        }
    } catch (final DataAccessException e) {
        throw new PreventedException("SQL exception while executing query for " + username, e);
    }

    String encryptedPassword = (String) userDetails.get(fieldPassword);

    if (!isPasswordValid(password, encryptedPassword)) {
        throw new FailedLoginException("incorrect password specified for username " + username);
    }

    return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null);
}

From source file:eu.forgestore.ws.util.ShiroUTValidator.java

public String validate(UsernameToken usernameToken) throws LoginException {

    if (usernameToken == null) {
        throw new SecurityException("noCredential");
    }/*from   www. j  av a  2s . com*/
    // Validate the UsernameToken

    String pwType = usernameToken.getPasswordType();
    logger.info("UsernameToken user " + usernameToken.getName());
    logger.info("UsernameToken password " + usernameToken.getPassword());
    logger.info("UsernameToken password type " + pwType);

    //      if (!WSConstants.PASSWORD_TEXT.equals(pwType)) {
    //         if (log.isDebugEnabled()) {
    //            logger.debug("Authentication failed - digest passwords are not accepted");
    //         }
    //         throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
    //      }

    if (usernameToken.getPassword() == null) {

        logger.debug("Authentication failed - no password was provided");

        throw new FailedLoginException("Sorry! No login for you.");
    }

    // Validate it via Shiro
    Subject currentUser = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(usernameToken.getName(),
            usernameToken.getPassword());
    token.setRememberMe(true);
    try {
        currentUser.login(token);
        currentUser.getSession().setAttribute("aKey", UUID.randomUUID().toString());
    } catch (AuthenticationException ex) {
        logger.info(ex.getMessage(), ex);
        throw new FailedLoginException("Sorry! No login for you.");
    }
    // Perform authorization check
    if (!requiredRoles.isEmpty() && !currentUser.hasAllRoles(requiredRoles)) {
        logger.info("Authorization failed for authenticated user");
        throw new FailedLoginException("Sorry! No login for you.");
    }

    return (String) currentUser.getPrincipal();
}

From source file:org.gluu.oxauth.cas.auth.handler.ClientAuthenticationHandler.java

/**
 * {@inheritDoc}//from  w  w  w .jav  a 2  s  .  co m
 */
@Override
protected HandlerResult doAuthentication(final Credential credential)
        throws GeneralSecurityException, PreventedException {
    final ClientCredential clientCredentials = (ClientCredential) credential;
    logger.debug("Client credentials : '{}'", clientCredentials);

    final String clientName = clientCredentials.getClientName();
    logger.debug("Client name : '{}'", clientName);

    // Web context
    final ServletExternalContext servletExternalContext = (ServletExternalContext) ExternalContextHolder
            .getExternalContext();
    final HttpServletRequest request = (HttpServletRequest) servletExternalContext.getNativeRequest();
    final HttpServletResponse response = (HttpServletResponse) servletExternalContext.getNativeResponse();
    final WebContext webContext = new J2EContext(request, response);

    // Get user profile
    final UserProfile userProfile = this.client.getUserProfile(clientCredentials, webContext);
    logger.debug("userProfile : {}", userProfile);

    if (userProfile != null) {
        final String id = userProfile.getId();
        if (StringHelper.isNotEmpty(id)) {
            clientCredentials.setUserProfile(userProfile);

            return new HandlerResult(this, clientCredentials,
                    new SimplePrincipal(id, userProfile.getAttributes()));
        }
    }

    throw new FailedLoginException("Provider did not produce profile for " + clientCredentials);
}

From source file:org.jasig.cas.support.pac4j.authentication.handler.support.AbstractClientAuthenticationHandler.java

@Override
protected HandlerResult doAuthentication(final Credential credential)
        throws GeneralSecurityException, PreventedException {
    final ClientCredential clientCredentials = (ClientCredential) credential;
    logger.debug("clientCredentials : {}", clientCredentials);

    final String clientName = clientCredentials.getCredentials().getClientName();
    logger.debug("clientName : {}", clientName);

    // get client
    final Client<Credentials, UserProfile> client = this.clients.findClient(clientName);
    logger.debug("client : {}", client);

    // web context
    final ServletExternalContext servletExternalContext = (ServletExternalContext) ExternalContextHolder
            .getExternalContext();/*from ww w  .  j a v  a 2 s .  co  m*/
    final HttpServletRequest request = (HttpServletRequest) servletExternalContext.getNativeRequest();
    final HttpServletResponse response = (HttpServletResponse) servletExternalContext.getNativeResponse();
    final WebContext webContext = new J2EContext(request, response);

    // get user profile
    final UserProfile userProfile = client.getUserProfile(clientCredentials.getCredentials(), webContext);
    logger.debug("userProfile : {}", userProfile);

    if (userProfile != null) {
        return createResult(clientCredentials, userProfile);
    }

    throw new FailedLoginException("Provider did not produce a user profile for: " + clientCredentials);
}

From source file:io.fabric8.maven.impl.MavenSecureHttpContext.java

public Subject doAuthenticate(final String username, final String password) {
    try {//  w w  w. j  a  v a2 s  .c  o m
        Subject subject = new Subject();
        LoginContext loginContext = new LoginContext(realm, subject, 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(username);
                    } else if (callbacks[i] instanceof PasswordCallback) {
                        ((PasswordCallback) callbacks[i]).setPassword(password.toCharArray());
                    } else {
                        throw new UnsupportedCallbackException(callbacks[i]);
                    }
                }
            }
        });
        loginContext.login();
        if (role != null && role.length() > 0) {
            String clazz = "org.apache.karaf.jaas.boot.principal.RolePrincipal";
            String name = role;
            int idx = role.indexOf(':');
            if (idx > 0) {
                clazz = role.substring(0, idx);
                name = role.substring(idx + 1);
            }
            boolean found = false;
            for (Principal p : subject.getPrincipals()) {
                if (p.getClass().getName().equals(clazz) && p.getName().equals(name)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new FailedLoginException("User does not have the required role " + role);
            }
        }
        return subject;
    } catch (AccountException e) {
        LOGGER.warn("Account failure", e);
        return null;
    } catch (LoginException e) {
        LOGGER.debug("Login failed", e);
        return null;
    } catch (GeneralSecurityException e) {
        LOGGER.error("General Security Exception", e);
        return null;
    }
}

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

public boolean login() throws LoginException {
    try {//from   w  ww  .  ja va2 s.  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;
}