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

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

Introduction

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

Prototype

public AuthenticationException(Throwable cause) 

Source Link

Document

Constructs a new AuthenticationException.

Usage

From source file:com.yea.shiro.realm.jdbc.JdbcRealm.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//w w  w .  java 2 s  .  c  o m
protected Map<String, Object> getUser(String username) throws AuthenticationException {
    List<Map<String, Object>> listUser;
    try {
        listUser = (List<Map<String, Object>>) shiroDao
                .executeSQL(ShiroConstants.ShiroSQL.AUTHENTICATION_QUERY.getSql(), new String[] { username });
        if (listUser == null || listUser.size() == 0) {
            throw new UnknownAccountException("??[" + username + "]?");
        } else if (listUser.size() > 1) {
            throw new AuthenticationException("?[" + username
                    + "]???????");
        } else {
            return listUser.get(0);
        }
    } catch (Exception e) {
        final String message = "[" + username + "]??SQL error";
        throw new AuthenticationException(message, e);
    }
}

From source file:com.yiguang.payment.rbac.controller.ShiroDbRealm.java

License:Apache License

/**
 * ??// www .ja  v a 2 s. c  o  m
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
        throws AuthenticationException {
    User user = (User) principals.getPrimaryPrincipal();
    if (user != null) {

        List<RoleUser> roleUserList = roleUserService.queryRoleUserByUserId(user.getId());
        List<Role> roleList = new ArrayList<Role>();
        for (RoleUser roleUser : roleUserList) {
            long roleId = roleUser.getRoleId();
            Role role = roleService.queryRole(roleId);
            roleList.add(role);
        }
        if (roleList != null && roleList.size() != 0) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            for (Role role : roleList) {
                //               List<String> permissions = rolePrivilegeQueryService.queryPermissionsByRoleId(role.getId());
                //               info.addRole(role.getRoleName());
                //               info.addStringPermissions(permissions);
            }
            return info;
        } else {
            throw new AuthenticationException("??");
        }
    } else {
        throw new AuthenticationException("?????");
    }
}

From source file:com.yiguang.payment.rbac.controller.ShiroDbRealm.java

License:Apache License

/**
 * ??/*ww w.  j  a  v a 2 s.c  om*/
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
    String userName = token.getUsername();
    String pwd = null;
    if (!StringUtil.isNullOrEmpty(userName)) {
        User user = userService.queryUserByName(userName);
        if (user != null) {
            if (CommonConstant.CommonStatus.CLOSE == user.getStatus()) {
                throw new LockedAccountException("?????");
            }

            String loginPwd = user.getPassword();

            pwd = String.valueOf(token.getPassword());
            String md5Password = securityKeystoreService.getEncryptKeyByJSRSAKey(pwd, user.getId());
            if (!md5Password.equals(loginPwd)) {
                throw new IncorrectCredentialsException("????");
            }
            token.setPassword(md5Password.toCharArray());
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, loginPwd,
                    getName());
            return simpleAuthenticationInfo;
        } else {
            throw new UnknownAccountException("???!");
        }
    } else {
        throw new AuthenticationException("????");
    }
}

From source file:com.zrk.oauthclient.shiro.support.UsernamePasswordAndClientRealm.java

License:Apache License

@SuppressWarnings("unchecked")
protected AuthenticationInfo internalClientGetAuthenticationInfo(
        final AuthenticationToken authenticationToken) {
    final UsernamePasswordAndClientToken clientToken = (UsernamePasswordAndClientToken) authenticationToken;
    log.debug("clientToken : {}", clientToken);
    if (clientToken == null) {
        return null;
    }/*from   w  w w . ja  v  a 2s  . co  m*/

    final Credentials credentials = (Credentials) clientToken.getCredentials();
    log.debug("credentials : {}", credentials);

    final Client<Credentials, CommonProfile> client = this.clients.findClient(clientToken.getClientName());
    log.debug("client : {}", client);

    final CommonProfile profile = client.getUserProfile(credentials, clientToken.getContext());
    log.debug("profile : {}", profile);

    if (profile == null) {
        final String message = "No profile retrieved from authentication using client : " + client
                + " and credentials : " + credentials;
        log.info(message);
        throw new AuthenticationException(message);
    }

    // refresh authentication token with user id
    final String userId = profile.getTypedId();
    clientToken.setUserId(userId);
    // set rememberMe status
    clientToken.setRememberMe(profile.isRemembered());
    return internalClientGetAuthenticationInfo(profile, credentials);
}

From source file:ddf.security.realm.sts.AbstractStsRealm.java

License:Open Source License

/**
 * Perform authentication based on the supplied token.
 *//*  w w  w . j a  v a  2 s . c o m*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
    String method = "doGetAuthenticationInfo(    AuthenticationToken token )";
    LOGGER.entry(method);

    Object credential;

    if (token instanceof SAMLAuthenticationToken) {
        credential = token.getCredentials();
    } else if (token instanceof BaseAuthenticationToken) {
        credential = ((BaseAuthenticationToken) token).getCredentialsAsXMLString();
    } else {
        credential = token.getCredentials().toString();
    }
    if (credential == null) {
        String msg = "Unable to authenticate credential.  A NULL credential was provided in the supplied authentication token. This may be due to an error with the SSO server that created the token.";
        LOGGER.error(msg);
        throw new AuthenticationException(msg);
    } else {
        //removed the credentials from the log message for now, I don't think we should be dumping user/pass into log
        LOGGER.debug("Received credentials.");
    }

    if (!settingsConfigured) {
        configureStsClient();
        settingsConfigured = true;
    } else {
        setClaimsOnStsClient(createClaimsElement());
    }

    SecurityToken securityToken;
    if (token instanceof SAMLAuthenticationToken && credential instanceof SecurityToken) {
        securityToken = renewSecurityToken((SecurityToken) credential);
    } else {
        securityToken = requestSecurityToken(credential);
    }

    LOGGER.debug("Creating token authentication information with SAML.");
    SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo();
    SimplePrincipalCollection principals = new SimplePrincipalCollection();
    SecurityAssertion assertion = new SecurityAssertionImpl(securityToken);
    principals.add(assertion.getPrincipal(), NAME);
    principals.add(assertion, NAME);
    simpleAuthenticationInfo.setPrincipals(principals);
    simpleAuthenticationInfo.setCredentials(credential);

    LOGGER.exit(method);
    return simpleAuthenticationInfo;
}

From source file:de.fatalix.app.bl.authentication.JPARealm.java

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (token == null) {
        throw new AuthenticationException("PrincipalCollection method argument cannot be null.");
    }/*ww  w .j a v a  2  s. c  o m*/

    UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
    AppUser user = service.getAppUser(usernamePasswordToken.getUsername());
    if (user == null) {
        throw new AuthenticationException("Could not find user");
    }
    if (getCredentialsMatcher().doCredentialsMatch(usernamePasswordToken, user.getAsAuthenticationInfo())) {
        return user.getAsAuthenticationInfo();
    }

    throw new AuthenticationException("Failed to authenticate");
}

From source file:de.fatalix.bookery.bl.authentication.JPARealm.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (!(token instanceof UsernamePasswordToken)) {
        throw new IllegalStateException("Token has to be instance of UsernamePasswordToken class");
    }//from  ww w .j av a  2  s  . c o  m

    UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
    if (usernamePasswordToken.getUsername() == null) {
        throw new AccountException("Null usernames are not allowed by this realm.");
    }

    AppUser user = service.getAppUser(usernamePasswordToken.getUsername());
    if (user == null) {
        throw new AuthenticationException("Could not find user");
    }

    if (getCredentialsMatcher().doCredentialsMatch(usernamePasswordToken, user.getAsAuthenticationInfo())) {
        return user.getAsAuthenticationInfo();
    }

    throw new AuthenticationException("Failed to authenticate!");
}

From source file:de.lemo.apps.services.security.BasicSecurityRealm.java

License:Open Source License

@Override
@Log//from www .ja  v a 2  s. c o m
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token)
        throws AuthenticationException {

    final UsernamePasswordToken userToken = (UsernamePasswordToken) token;
    final String username = userToken.getUsername();
    final String password = String.copyValueOf(userToken.getPassword());

    final User loginUser = userDAO.getUser(userToken.getUsername());

    AuthenticationInfo authInfo = null;

    if (loginUser == null) {
        logger.debug("Login: The user " + username + " doesn't exist.");
        throw new AuthenticationException("The user " + username + " doesn't exist.");
    } else if (loginUser.checkPassword(password)) {
        logger.debug("Login: User " + username + " logged in successfully.");
        authInfo = new SimpleAuthenticationInfo(userToken.getUsername(), userToken.getPassword(), "basic");
    }

    return authInfo;
}

From source file:demo.learn.shiro.realm.CustomRealm.java

License:Apache License

/**
 * Gets the user's password + salt.//from  w w  w  . j a va 2 s . c  om
 * @param conn {@link Connection}.
 * @param username Username.
 * @return String array of length 2. 0-th index string is
 * password and 1-st index string is password salt.
 * @throws SQLException
 */
@SuppressWarnings("resource")
protected String[] getUserPassword(Connection conn, String username) throws SQLException {

    String[] result;
    boolean returningSeparatedSalt = false;
    switch (saltStyle) {
    case NO_SALT:
    case CRYPT:
    case EXTERNAL:
        result = new String[1];
        break;
    default:
        result = new String[2];
        returningSeparatedSalt = true;
    }

    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(authenticationQuery);
        ps.setString(1, username);

        // Execute query
        rs = ps.executeQuery();

        // Loop over results - although we are only expecting one result, since usernames should be unique
        boolean foundResult = false;
        while (rs.next()) {

            // Check to ensure only one row is processed
            if (foundResult) {
                throw new AuthenticationException(
                        "More than one user row found for user [" + username + "]. Usernames must be unique.");
            }

            result[0] = rs.getString(1);
            if (returningSeparatedSalt) {
                result[1] = rs.getString(2);
            }

            foundResult = true;
        }
    } finally {
        JdbcUtils.closeResultSet(rs);
        JdbcUtils.closeStatement(ps);
    }

    return result;
}

From source file:edu.usu.sdl.opencatalog.security.OpenAmRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    WebTarget target = restClient("json/authenticate");
    UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
    Response response = target.request(MediaType.APPLICATION_JSON)
            .header("X-OpenAM-Username", usernamePasswordToken.getUsername())
            .header("X-OpenAM-Password", String.valueOf(usernamePasswordToken.getPassword())).post(null);

    OpenAmResponse openAmResponse = response.readEntity(OpenAmResponse.class);
    if (StringUtils.isNotBlank(openAmResponse.getTokenId())) {
        OpenAmAccount account = populateAccount(openAmResponse.getTokenId(), token.getPrincipal().toString());
        account.setCredentials(usernamePasswordToken.getPassword());
        return account;
    } else {//  w  ww . ja va 2s  .  c o m
        throw new AuthenticationException(openAmResponse.getReason());
    }
}