Example usage for org.apache.shiro.authc SimpleAuthenticationInfo setCredentialsSalt

List of usage examples for org.apache.shiro.authc SimpleAuthenticationInfo setCredentialsSalt

Introduction

In this page you can find the example usage for org.apache.shiro.authc SimpleAuthenticationInfo setCredentialsSalt.

Prototype

public void setCredentialsSalt(ByteSource salt) 

Source Link

Document

Sets the salt used to hash the credentials, or null if no salt was used or credentials were not hashed at all.

Usage

From source file:aaa.realms.MySQLRealm.java

License:Apache License

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    VTNAuthNToken upToken = (VTNAuthNToken) token;
    String username = upToken.getUsername();
    String domainID = Integer.toString(upToken.getDomainId());
    // Null username is invalid
    if (username == null) {
        throw new AccountException("Null usernames are not allowed by this realm.");
    }/* w  ww.  ja  v  a2  s .c om*/

    Connection conn = null;
    SimpleAuthenticationInfo info = null;
    try {
        conn = dataSource.getConnection();
        Set<String> domains = getUserDomain(conn, username);
        if (!(domains.contains(domainID))) {
            throw new AuthenticationException("Domain not found");
        }

        String password = null;
        String salt = null;
        switch (saltStyle) {
        case NO_SALT:
            password = getPasswordForUser(conn, username)[0];
            break;
        case CRYPT:
            // TODO: separate password and hash from getPasswordForUser[0]
            throw new ConfigurationException("Not implemented yet");
            //break;
        case COLUMN:
            String[] queryResults = getPasswordForUser(conn, username);
            password = queryResults[0];
            salt = queryResults[1];
            break;
        case EXTERNAL:
            password = getPasswordForUser(conn, username)[0];
            salt = getSaltForUser(username);
        }

        if (password == null) {
            throw new UnknownAccountException("No account found for user [" + username + "]");
        }

        info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());

        if (salt != null) {
            info.setCredentialsSalt(ByteSource.Util.bytes(salt));
        }

    } catch (SQLException e) {
        final String message = "There was a SQL error while authenticating user [" + username + "]";
        if (log.isErrorEnabled()) {
            log.error(message, e);
        }

        // Rethrow any SQL errors as an authentication exception
        throw new AuthenticationException(message, e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }

    return info;
}

From source file:annis.security.ANNISUserRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    Validate.isInstanceOf(String.class, token.getPrincipal());

    String userName = (String) token.getPrincipal();
    if (userName.equals(anonymousUser)) {
        // for anonymous users the user name equals the Password, so hash the user name
        Sha256Hash hash = new Sha256Hash(userName);
        return new SimpleAuthenticationInfo(userName, hash.getBytes(), ANNISUserRealm.class.getName());
    }//from w w w.j a v a 2 s. c o m

    User user = confManager.getUser(userName);
    if (user != null) {
        String passwordHash = user.getPasswordHash();
        if (passwordHash != null) {
            if (passwordHash.startsWith("$")) {
                Shiro1CryptFormat fmt = new Shiro1CryptFormat();
                Hash hashCredentials = fmt.parse(passwordHash);
                if (hashCredentials instanceof SimpleHash) {
                    SimpleHash simpleHash = (SimpleHash) hashCredentials;

                    Validate.isTrue(simpleHash.getIterations() == 1,
                            "Hash iteration count must be 1 for every password hash!");

                    // actually set the information from the user file
                    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName,
                            simpleHash.getBytes(), ANNISUserRealm.class.getName());
                    info.setCredentialsSalt(new SerializableByteSource(simpleHash.getSalt()));
                    return info;
                }
            } else {
                // fallback unsalted hex hash
                SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(), passwordHash,
                        ANNISUserRealm.class.getName());
                return info;
            }

        }
    }
    return null;
}

From source file:br.com.betsportclub.controller.security.SecurityRealm.java

License:Apache License

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    String username = upToken.getUsername();

    // Null username is invalid
    if (username == null) {
        throw new AccountException("Null usernames are not allowed by this realm.");
    }/*  w w w  . ja  v  a 2s. c o  m*/

    Connection conn = null;
    SimpleAuthenticationInfo info = null;
    try {
        conn = dataSource.getConnection();

        String password = null;
        String salt = null;
        switch (saltStyle) {
        case NO_SALT:
            password = getPasswordForUser(conn, username)[0];
            break;
        case CRYPT:
            // TODO: separate password and hash from getPasswordForUser[0]
            throw new ConfigurationException("Not implemented yet");
            //break;
        case COLUMN:
            String[] queryResults = getPasswordForUser(conn, username);
            password = queryResults[0];
            salt = queryResults[1];
            break;
        case EXTERNAL:
            password = getPasswordForUser(conn, username)[0];
            salt = getSaltForUser(username);
        }

        if (password == null) {
            throw new UnknownAccountException("No account found for user [" + username + "]");
        }

        info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());

        if (salt != null) {
            info.setCredentialsSalt(ByteSource.Util.bytes(salt));
        }

    } catch (SQLException e) {
        final String message = "There was a SQL error while authenticating user [" + username + "]";
        if (log.isErrorEnabled()) {
            log.error(message, e);
        }

        // Rethrow any SQL errors as an authentication exception
        throw new AuthenticationException(message, e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }

    return info;
}

From source file:cn.itganhuo.app.web.shiro.ShiroDbRealm.java

License:Apache License

/**
 * ????/*  ww w .j  a  va 2 s  . c o  m*/
 *
 * @version 0.0.1-SNAPSHOT
 * @author -?
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    log.debug("Began to validate user credentials.");

    UsernamePasswordToken uptoken = (UsernamePasswordToken) token;
    User user = userService.loadByAccount(uptoken.getUsername());
    if (user != null && StringUtil.hasText(user.getAccount())) {
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(),
                getName());
        info.setCredentialsSalt(ByteSource.Util.bytes(uptoken.getUsername() + user.getSalt()));
        return info;
    } else {
        return null;
    }
}

From source file:com.charmyin.shiro.realm.jdbc.JMongodbRealm.java

License:Apache License

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    String username = upToken.getUsername();

    // Null username is invalid
    if (username == null) {
        throw new AccountException("Null usernames are not allowed by this realm.");
    }// w  w  w  .  ja  v  a 2  s .co  m

    SimpleAuthenticationInfo info = null;
    try {
        //conn = dataSource.getConnection();

        String password = null;
        String salt = null;
        switch (saltStyle) {
        case NO_SALT:
            password = getPasswordForUser(username)[0];
            break;
        case CRYPT:
            // TODO: separate password and hash from getPasswordForUser[0]
            throw new ConfigurationException("Not implemented yet");
            //break;
        case COLUMN:
            String[] queryResults = getPasswordForUser(username);
            password = queryResults[0];
            salt = queryResults[1];
            break;
        case EXTERNAL:
            password = getPasswordForUser(username)[0];
            salt = getSaltForUser(username);
        }

        if (password == null) {
            throw new UnknownAccountException("No account found for user [" + username + "]");
        }

        info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());

        if (salt != null) {
            info.setCredentialsSalt(ByteSource.Util.bytes(salt));
        }

    } catch (MongoException e) {
        final String message = "There was a SQL error while authenticating user [" + username + "]";
        if (log.isErrorEnabled()) {
            log.error(message, e);
        }

        // Rethrow any SQL errors as an authentication exception
        throw new AuthenticationException(message, e);
    }

    return info;
}

From source file:com.cssnb.commons.shiro.MyJdbcRealm.java

License:Apache License

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    //UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    CaptchaUsernamePasswordToken upToken = (CaptchaUsernamePasswordToken) token;

    //?? ?/*from   ww w .j  a  v  a2s  . c om*/
    String captcha = null;
    Object obj_captcha = SecurityUtils.getSubject().getSession().getAttribute(Constants.CAPTCHA_KEY);
    //Object obj_count = SecurityUtils.getSubject().getSession().getAttribute( "login_fail_count" );
    //int failed_count = (obj_count ==null || !(obj_count instanceof Integer))?0:(Integer)obj_count;
    if (obj_captcha instanceof String)
        captcha = (String) obj_captcha;
    log.debug("you input:{},img:{}", upToken.getCaptcha(), captcha);
    if (captcha != null
            //&& failed_count >0
            && !captcha.equalsIgnoreCase(upToken.getCaptcha())) {
        throw new IncorrectCaptchaException("???");
    }

    String username = upToken.getUsername();

    // Null username is invalid
    if (username == null) {
        throw new AccountException("Null usernames are not allowed by this realm.");
    }

    Connection conn = null;
    SimpleAuthenticationInfo info = null;
    try {
        conn = dataSource.getConnection();

        String password = null;
        String salt = null;
        switch (saltStyle) {
        case NO_SALT:
            password = getPasswordForUser(conn, username)[0];
            break;
        case CRYPT:
            // TODO: separate password and hash from getPasswordForUser[0]
            throw new ConfigurationException("Not implemented yet");
            //break;
        case COLUMN:
            String[] queryResults = getPasswordForUser(conn, username);
            password = queryResults[0];
            salt = queryResults[1];
            break;
        case EXTERNAL:
            password = getPasswordForUser(conn, username)[0];
            salt = getSaltForUser(username);
        }

        if (password == null) {
            throw new UnknownAccountException("No account found for user [" + username + "]");
        }

        info = new SimpleAuthenticationInfo(new ShiroUser(username, username), password.toCharArray(),
                getName());

        if (salt != null) {
            info.setCredentialsSalt(ByteSource.Util.bytes(salt));
        }

    } catch (SQLException e) {
        final String message = "There was a SQL error while authenticating user [" + username + "]";
        if (log.isErrorEnabled()) {
            log.error(message, e);
        }

        // Rethrow any SQL errors as an authentication exception
        throw new AuthenticationException(message, e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }

    return info;
}

From source file:com.devcru.shirosandbox.realm.SaltAwareJdbcRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    String username = upToken.getUsername();

    // Null username is invalid
    if (username == null) {
        throw new AccountException("Null usernames are not allowed by this realm.");
    }//from   ww  w .j av a  2  s. co  m

    Connection conn = null;
    AuthenticationInfo info = null;
    try {
        conn = dataSource.getConnection();

        String password = getPasswordForUser(conn, username);

        if (password == null) {
            throw new UnknownAccountException("No account found for user [" + username + "]");
        }

        SimpleAuthenticationInfo saInfo = new SimpleAuthenticationInfo(username, password, getName());
        /**
         * This (very bad) example uses the username as the salt in this sample app.  DON'T DO THIS IN A REAL APP!
         *
         * Salts should not be based on anything that a user could enter (attackers can exploit this).  Instead
         * they should ideally be cryptographically-strong randomly generated numbers.
         */
        saInfo.setCredentialsSalt(ByteSource.Util.bytes(username));

        info = saInfo;

    } catch (SQLException e) {
        final String message = "There was a SQL error while authenticating user [" + username + "]";
        if (log.isErrorEnabled()) {
            log.error(message, e);
        }

        // Rethrow any SQL errors as an authentication exception
        throw new AuthenticationException(message, e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }

    return info;
}

From source file:com.github.pires.example.shiro.SMRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    final String email = upToken.getUsername();

    // null email is invalid
    if (email == null) {
        throw new AccountException("Null email is not allowed by this realm.");
    }//w w  w .ja v  a  2 s.co m

    Connection conn = null;
    SimpleAuthenticationInfo info = null;
    try {
        conn = dataSource.getConnection();
        String password = null;
        String salt = null;
        switch (saltStyle) {
        case NO_SALT:
            password = getPasswordForUser(conn, email)[0];
            break;
        case CRYPT:
            // TODO: separate password and hash from getPasswordForUser[0]
            throw new ConfigurationException("Not implemented yet");
            // break;
        case COLUMN:
            String[] queryResults = getPasswordForUser(conn, email);
            password = queryResults[0];
            salt = queryResults[1];
            break;
        case EXTERNAL:
            password = getPasswordForUser(conn, email)[0];
            salt = getSaltForUser(email);
        }

        if (password == null) {
            throw new UnknownAccountException("No account found for user identified by [" + email + "]");
        }
        info = new SimpleAuthenticationInfo(email, password.toCharArray(), getName());
        if (salt != null) {
            info.setCredentialsSalt(ByteSource.Util.bytes(salt));
        }
    } catch (SQLException e) {
        final String message = "There was a SQL error while authenticating user identified by [" + email + "]";
        logger.error(message, e);
        // rethrow any SQL errors as an authentication exception
        throw new AuthenticationException(message, e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }

    return info;
}

From source file:com.greenline.hrs.admin.auth.realm.WebRealm.java

License:Open Source License

/**
 * Retrieves authentication data from an implementation-specific datasource (RDBMS, LDAP, etc) for the given
 * authentication token./* ww w  . ja  v  a  2 s.  co  m*/
 * <p/>
 * For most datasources, this means just 'pulling' authentication data for an associated subject/user and nothing
 * more and letting Shiro do the rest.  But in some systems, this method could actually perform EIS specific
 * log-in logic in addition to just retrieving data - it is up to the Realm implementation.
 * <p/>
 * A {@code null} return value means that no account could be associated with the specified token.
 *
 * @param token the authentication token containing the user's principal and credentials.
 * @return an {@link org.apache.shiro.authc.AuthenticationInfo} object containing account data resulting from the
 * authentication ONLY if the lookup is successful (i.e. account exists and is valid, etc.)
 * @throws org.apache.shiro.authc.AuthenticationException if there is an error acquiring data or performing
 *                                                        realm-specific authentication logic for the specified <tt>token</tt>
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    String username = upToken.getUsername();
    String encryptPasswd = new String(upToken.getPassword());
    SimpleAuthenticationInfo authInfo = null;
    UserPassport userPassport = null;
    try {
        userPassport = manUserService.getUserPassportFromEncryptedPwd(Long.valueOf(username), encryptPasswd);
    } catch (Exception e) {
        LOG.error(AuthMessageConstants.AUTHORICATION_EXCEPTION, e);
        throw new AuthenticationException(AuthMessageConstants.AUTHORICATION_EXCEPTION, e);
    }
    if (userPassport == null) {
        throw new AuthenticationException(AuthMessageConstants.USER_PWD_ILLEGAL);
    }
    authInfo = new SimpleAuthenticationInfo(username, userPassport.getPassword(), getName());
    authInfo.setCredentialsSalt(ByteSource.Util.bytes(userPassport.getSalt()));
    return authInfo;
}

From source file:com.myproject.poverty.console.config.ShiroDbRealm.java

License:Apache License

/**
 * ?,./*  w  ww  .  j  a v a 2  s. c  o  m*/
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    String userAccount = ((UsernamePasswordToken) authcToken).getUsername();
    List<BasicUser> users = basicUserService.findByUserAccount(userAccount);
    if (users == null || (users != null && users.size() == 0)) {
        throw new ServiceException("???");
    } else if (users != null && users.size() > 1) {
        throw new ServiceException("???????");
    }
    BasicUser user = users.get(0);
    ShiroUser su = new ShiroUser();
    su.setUserId(user.getUserId());
    su.setUserAccount(user.getUserAccount());
    su.setUserName(user.getUserName());
    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(su, user.getPassword(),
            getName());
    authenticationInfo.setCredentialsSalt(
            ByteSource.Util.bytes(user.getUserAccount() + user.getSalt() + ShiroUtils.ENCRYPTION_TEXT));
    return authenticationInfo;
}