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

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

Introduction

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

Prototype

public SimpleAuthenticationInfo(PrincipalCollection principals, Object hashedCredentials,
        ByteSource credentialsSalt) 

Source Link

Document

Constructor that takes in an account's identifying principal(s), hashed credentials used to verify the principals, and the salt used when hashing the credentials.

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.");
    }//from w ww  .ja va 2s . c o  m

    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:action.ShiroDbRealm.java

License:Apache License

/**
 * ?,.//w  w w  .  j a  v a  2 s  .com
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
    User user = userService.getByUserName(token.getUsername());
    if (user != null) {
        return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getUsername(), user.getName()),
                user.getPassword(), getName());
    } else {
        return null;
    }
}

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 ww. j  a  v a2  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:au.org.theark.core.security.AAFRealm.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    SimpleAuthenticationInfo sai = null;
    ArkUserVO userVO = null;/*w  ww .j a v a  2s .  c  o m*/
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
    //log.info("IN AAFRealm.doGetAuthenticationInfo");
    //log.info("authToken: " + authcToken.getPrincipal().toString());
    log.info("AAF token username: " + token.getUsername());

    try {
        //log.info("checking user");
        userVO = iArkCommonService.getUser(token.getUsername().trim());
        if (userVO != null) {
            // Check if the user is in the Ark Database
            ArkUser arkUser = iArkCommonService.getArkUser(token.getUsername().trim());
            // Also check if the Ark User is linked with any study and has roles.
            // If no roles found, stop the user from logging in until an administrator has set it up
            if (!iArkCommonService.isArkUserLinkedToStudies(arkUser)) {
                throw new UnknownAccountException(UNKNOWN_ACCOUNT);
            }

            final WebRequest webRequest = (WebRequest) RequestCycle.get().getRequest();
            final HttpServletRequest httpReq = (HttpServletRequest) webRequest.getContainerRequest();

            //log.info("checking shib headers");
            String userName = httpReq.getHeader("AJP_mail");
            String password = httpReq.getHeader("AJP_Shib-Session-ID");

            if (userName != null && password != null) {
                //log.info("creating SimpleAuthenticationInfo");
                sai = new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName());
            }
        }
    } catch (ArkSystemException e) {
        log.error(e.getMessage());
    } catch (EntityNotFoundException e) {
        throw new UnknownAccountException(UNKNOWN_ACCOUNT);
    }
    return sai;
}

From source file:au.org.theark.core.security.ArkLdapRealm.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    SimpleAuthenticationInfo sai = null;
    ArkUserVO userVO = null;/*from  w w w.j  a  v a  2  s .co m*/
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

    try {
        userVO = iArkCommonService.getUser(token.getUsername().trim());// Example to use core services to get user
        if (userVO != null) {
            // Check if the user is in the Ark Database
            ArkUser arkUser = iArkCommonService.getArkUser(token.getUsername().trim());
            // Also check if the Ark User is linked with any study and has roles.
            // If no roles found, stop the user from logging in until an administrator has set it up
            if (!iArkCommonService.isArkUserLinkedToStudies(arkUser)) {
                throw new UnknownAccountException(UNKNOWN_ACCOUNT);
            }

            sai = new SimpleAuthenticationInfo(userVO.getUserName(), userVO.getPassword(), getName());
        }
    } catch (ArkSystemException e) {
        log.error(e.getMessage());
    } catch (EntityNotFoundException e) {
        throw new UnknownAccountException(UNKNOWN_ACCOUNT);
    }
    return sai;
}

From source file:b4f.seguridad.ShiroAuthorizingRealm.java

@Override
public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken)
        throws AuthenticationException {

    System.out.println("ShiroAuthorizingRealm.doGetAuthenticationInfo()");

    //SE ACCEDI CON UN JWT TOKEN
    if (authToken instanceof JwtToken) {
        JwtToken jwt = (JwtToken) authToken;
        if (jwt.getToken() != null && !jwt.getToken().equals("")) {

            if (!jwt.validar()) {
                throw new AuthenticationException("Token invalido.");
            }/*from w  w  w . j a v  a  2 s  . c  om*/

            try {
                Usuario user = UsersManager.getUser(jwt.getUser());
                AuthenticationInfo rta = new SimpleAuthenticationInfo(user.getUsuario(), user.getPassword(),
                        getName());
                return rta;
            } catch (Exception ex) {
                Logger.getLogger(ShiroAuthorizingRealm.class.getName()).log(Level.SEVERE, null, ex);
                throw new AuthenticationException(ex.getMessage());
            }

        } else {
            throw new AuthenticationException("Token invalido.");
        }
    }

    UsernamePasswordToken token = (UsernamePasswordToken) authToken;

    Usuario user;
    try {
        user = UsersManager.getUser(token.getUsername());

    } catch (Exception ex) {
        System.err.println("Error looking up user: " + ex.getMessage());
        throw new AuthenticationException("Usuario '" + token.getUsername() + "' no encontrado", ex);
    }

    if (user != null) {
        System.out.println("Returning user " + user.getUsuario() + " password " + user.getPassword());
        return new SimpleAuthenticationInfo(user.getUsuario(), user.getPassword(), getName());

    } else {
        System.err.println("Usuarioname not found: " + token.getUsername());
        throw new AuthenticationException("User not found: " + token.getUsername());
    }
}

From source file:base.web.ShiroDbRealm.java

License:Apache License

/**
 * ?,.//  w w  w  .  j  a  v  a 2 s  .co  m
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
    User user = userService.getByUserName(token.getUsername());
    if (user != null) {
        return new SimpleAuthenticationInfo(
                new ShiroUser(user.getId(), user.getUsername(), user.getName(), user.getSource()),
                user.getPassword(), getName());
    } else {
        return null;
    }
}

From source file:biz.neustar.nexus.plugins.gitlab.GitlabAuthenticatingRealm.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
        throws AuthenticationException {

    if (!(authenticationToken instanceof UsernamePasswordToken)) {
        throw new UnsupportedTokenException("Token of type " + authenticationToken.getClass().getName()
                + " is not supported.  A " + UsernamePasswordToken.class.getName() + " is required.");
    }/*from   w w w . j  a  v a 2  s  .co  m*/
    UsernamePasswordToken userPass = (UsernamePasswordToken) authenticationToken;
    String token = new String(userPass.getPassword());
    String username = userPass.getUsername();

    if (token.isEmpty()) {
        LOGGER.debug(GITLAB_MSG + "token for {} is empty", username);
        return null;
    }

    try {
        LOGGER.debug(GITLAB_MSG + "authenticating {}", username);

        LOGGER.debug(GITLAB_MSG + "null? " + (gitlab == null));
        LOGGER.debug(GITLAB_MSG + "null? " + (gitlab.getRestClient() == null));

        GitlabUser gitlabUser = gitlab.getRestClient().getUser(username, token);
        User user = gitlabUser.toUser();
        if (user.getStatus() != UserStatus.active) {
            LOGGER.debug(GITLAB_MSG + "authentication failed {}", user);
            throw new AuthenticationException(DISABLED_USER_MESSAGE + " for " + username);
        }
        if (user.getUserId() == null || user.getUserId().isEmpty()) {
            LOGGER.debug(GITLAB_MSG + "authentication failed {}", user);
            throw new AuthenticationException(DEFAULT_MESSAGE + " for " + username);
        }
        LOGGER.debug(GITLAB_MSG + "successfully authenticated {}", username);
        return new SimpleAuthenticationInfo(gitlabUser, userPass.getCredentials(), getName());
    } catch (Exception e) {
        LOGGER.debug(GITLAB_MSG + "authentication failed {}", username);
        throw new AuthenticationException(DEFAULT_MESSAGE, e);
    }
}

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.  j ava  2 s  . 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:br.com.criativasoft.opendevice.restapi.auth.AccountDaoRealm.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {

    AccountAuth accountAuth = (AccountAuth) token;

    DataManager context = manager.getDataManager();

    if (context instanceof ApiDataManager) {

        AccountDao dao = ((ApiDataManager) context).getAccountDao();

        UserAccount userAccount = dao.getUserAccountByID(accountAuth.getUserAccountID());

        if (userAccount != null) {
            Account account = userAccount.getOwner();

            AccountType type = userAccount.getType();

            AccountPrincipal principal = new AccountPrincipal(userAccount.getUser().getId(),
                    userAccount.getId(), account.getUuid(), type);

            // todo: load permission tags into AuthenticationInfo
            return new SimpleAuthenticationInfo(principal, userAccount.getId(), "AccountDaoRealm");
        }//from ww w .j  a v  a2s .c om
    }

    return null;
}