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: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  w w.  ja v  a  2 s .  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:aaa.realms.MySQLRealm.java

License:Apache License

private String[] getPasswordForUser(Connection conn, String username) throws SQLException {

    String[] result;//from   ww  w. j  av  a  2s  .c  om
    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:b4f.seguridad.SecurityAuthenticator.java

@Override
public AuthenticationInfo authenticate(AuthenticationToken at) throws AuthenticationException {

    if (DEBUG) {/*from w w w . j a  v  a2 s. c  om*/
        System.out.println("[SECURITY AUTHENTICATOR] Autenticando: " + at);
    }

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

            if (!authToken.validar()) {
                throw new AccountException("Token invalido.");
            }

            try {
                Usuario user = UsersManager.getUser(authToken.getUser());
                if (user == null)
                    throw new Exception("Token invalido");

                SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo();
                authenticationInfo.setPrincipals(new SimplePrincipalCollection(user, user.getUsuario()));
                return authenticationInfo;
            } catch (Exception ex) {
                Logger.getLogger(ShiroAuthorizingRealm.class.getName()).log(Level.SEVERE, null, ex);
                throw new AuthenticationException(ex.getMessage());
            }

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

    DefaultSecurityManager dsm = new DefaultSecurityManager(getRealm());
    AuthenticationInfo authenticationInfo = dsm.authenticate(at);
    if (DEBUG) {
        System.out.println("[SECURITY AUTHENTICATOR] " + authenticationInfo);
    }
    return authenticationInfo;

}

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  av  a 2 s. co  m*/

            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: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.");
    }/* w  w  w. j av  a 2 s  .c o  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

private String[] getPasswordForUser(Connection conn, String username) throws SQLException {

    String[] result;/*from  w ww . ja  v  a  2 s  .  c  o m*/
    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 {

        authenticationQuery = authenticationQuery.replace("$ds_schema", schema);

        ps = conn.prepareStatement(authenticationQuery);
        ps.setString(1, username);
        //ps.setString(2, 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:br.com.criativasoft.opendevice.restapi.auth.GoogleAuthRealm.java

License:Open Source License

public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    GoogleAuthToken authToken = (GoogleAuthToken) token;

    String authTokenS = (String) authToken.getPrincipal();

    DefaultSecurityManager securityManager = (DefaultSecurityManager) SecurityUtils.getSecurityManager();
    Cache<Object, Object> cache = securityManager.getCacheManager().getCache(TOKEN_CACHE);

    DataManager context = manager.getDataManager();
    AccountDao dao = ((ApiDataManager) context).getAccountDao();

    String userAccountID = (String) cache.get(authTokenS);

    if (userAccountID == null) {

        log.warn("ApiKey not found for token : " + authTokenS);

        try {// www.j a va2  s .  co m
            String url = "https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=";
            CloseableHttpClient client = HttpClientBuilder.create().build();
            CloseableHttpResponse response = client.execute(new HttpGet(url + authTokenS));
            String bodyAsString = EntityUtils.toString(response.getEntity());

            if (response.getStatusLine().getStatusCode() == 200) {

                String appID = ODev.getConfig().getString(OpenDeviceConfig.ConfigKey.google_appid);

                if (appID == null) {
                    throw new AuthenticationException("Google AppID not configured !");
                }

                JsonNode json = new ObjectMapper().readTree(bodyAsString);

                String aud = json.get("aud").asText();

                // TODO: need validate, but this may ne used for another appletavions IDs (ALEXA, MIDDLEWARE)
                //                    if(!appID.equals(aud)){
                //                        throw new AuthenticationException("Invalid Google Token");
                //                    }

                UserDao userDao = ((ApiDataManager) context).getUserDao();
                User user = userDao.getUser(json.get("email").asText());

                // Store in cahe
                if (user != null) {
                    userAccountID = "" + user.getLasLoginAccount().getId();
                    cache.put(authTokenS, userAccountID);
                }

            } else {
                throw new AuthenticationException("Invalid Google Token");
            }

        } catch (IOException ex) {
            throw new AuthenticationException(ex.getMessage());
        }
    }

    if (userAccountID != null && context instanceof ApiDataManager) {

        UserAccount userAccount = dao.getUserAccountByID(Long.parseLong(userAccountID));

        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, authToken.getCredentials(), "BearerTokenRealm");
        }
    }

    return null;
}

From source file:br.com.criativasoft.opendevice.wsrest.filter.AuthenticationFilter.java

License:Open Source License

@Override
public ContainerRequest filter(ContainerRequest request) {

    // Ignore Web Resources.
    String path = request.getPath();
    if (WebUtils.isWebResource(path)) {
        return request;
    }/*from w  w w  . j  ava 2  s .co m*/

    Subject subject = SecurityUtils.getSubject();

    Session session = subject.getSession(false);

    if (session != null && subject.isAuthenticated()) {
        session.touch();
        return request;
    }

    if (!subject.isAuthenticated()) {

        // Google OAuth ( Ex.: Alexa Skill )
        String authorizationHeader = request.getHeaderValue(HttpHeaders.AUTHORIZATION);

        if (authorizationHeader != null && authorizationHeader.startsWith("Google")) {
            String token = authorizationHeader.substring("Google".length()).trim(); // Token

            GoogleAuthToken bearerToken = new GoogleAuthToken(token);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }

        }

        // Extract the token from the HTTP Authorization header (OAuth2)
        authorizationHeader = request.getHeaderValue(HttpHeaders.AUTHORIZATION);
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer")) {
            String token = authorizationHeader.substring("Bearer".length()).trim(); // API_KEY

            BearerAuthToken bearerToken = new BearerAuthToken(token);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }

        // ApiKey in Header (no 2 step auth)
        String header = request.getHeaderValue("ApiKey");
        if ((authorizationHeader != null && authorizationHeader.startsWith("ApiKey")) || header != null) {
            String apiKey = null;
            if (header != null) {
                apiKey = header;
            } else {
                apiKey = authorizationHeader.substring("ApiKey".length()).trim(); // API_KEY
            }

            if (StringUtils.isEmpty(apiKey)) {
                log.warn("ApiKey not found in Request");
                throw new AuthenticationException("ApiKey Required");
            }

            BearerAuthToken bearerToken = new BearerAuthToken(apiKey, true);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }

        // WebSocket HttpHeader Upgrade (JavaScript Library).
        header = request.getHeaderValue("Upgrade");
        if (header != null && header.contains("websocket")) {

            String apiKey = path.substring(path.lastIndexOf('/') + 1, path.length());

            BearerAuthToken bearerToken = new BearerAuthToken(apiKey, true);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }

        // Query Param (in URL)

        MultivaluedMap<String, String> queryParameters = request.getQueryParameters();

        List<String> apiKeyParams = queryParameters.get("ApiKey");

        if (apiKeyParams != null) {

            BearerAuthToken bearerToken = new BearerAuthToken(apiKeyParams.get(0), true);

            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }

        // GoogleAssistant / Dialogflow Integration
        header = request.getHeaderValue("GoogleAssistant");
        if (header != null && header.contains("Dialogflow")) {

            JsonNode entity = request.getEntity(JsonNode.class);
            JsonNode userNode = entity.get("originalDetectIntentRequest").get("payload").get("user");

            if (userNode == null) {
                log.warn("User not found in Request");
                throw new AuthenticationException("Invalid User / Token");
            }
            String token = userNode.get("accessToken").asText();

            BearerAuthToken bearerToken = new BearerAuthToken(token);

            // request.setEntityInputStream(new ByteArrayInputStream(entity.toString().getBytes()));
            request.setEntityInputStream(new ByteArrayInputStream(entity.toString().getBytes()));
            try {
                subject.login(bearerToken); // Use BearerTokenRealm
                return request;
            } catch (AuthenticationException e) {
                throw new AuthenticationException("Invalid AuthToken");
            }
        }
    }

    // NOTE: if not Autenticated, the UnauthenticatedException will throw (AuthorizationExceptionMap)

    return request;
}

From source file:br.com.criativasoft.opendevice.wsrest.resource.AuthRest.java

License:Open Source License

private Response doLogin(Subject currentUser, String username, String password, boolean isApiKey) {

    LOG.debug("Using ApiKey (" + isApiKey + "), username : " + username);

    Account account = null;/*from w w w .j a  v  a2 s  .  c  om*/
    String authtoken = null;
    boolean logged = false;

    // Login using: ApiKey
    if (isApiKey) {

        account = accountDao.getAccountByApiKey(username);

        // Generate and cache the 'AuthToken', this will be used in AuthenticationFilter
        // This token will be used in BearerTokenRealm
        // TODO: Need configure expire using EhCache
        if (account != null) {

            // NOTE(RR): To simplify the development of clients, AuthToken and API Key will be the AccountUUID.
            // This can be changed in the future (issues #57)
            // authtoken = UUID.randomUUID().toString();
            authtoken = account.getUuid();

            // Add token to cache (thid will be used in BearerTokenRealm)
            DefaultSecurityManager securityManager = (DefaultSecurityManager) SecurityUtils
                    .getSecurityManager();
            Cache<Object, Object> cache = securityManager.getCacheManager().getCache(TOKEN_CACHE);
            cache.put(authtoken, username); // username (is Api_Key in this case)
            logged = true;
        }

        // login using: Form
    } else if (!currentUser.isAuthenticated()) {

        try {

            User user = userDao.getUser(username);

            if (user == null)
                throw new AuthenticationException("Incorrect username");

            // ckeck plain version (loaded from database)
            boolean passwordsMatch = password.equals(user.getPassword());

            // Check encryption version (provided by user)
            if (!passwordsMatch) {
                HashingPasswordService service = new DefaultPasswordService();
                passwordsMatch = service.passwordsMatch(password, user.getPassword());
            }

            if (!passwordsMatch)
                throw new AuthenticationException("Incorrect password");

            Set<UserAccount> uaccounts = user.getAccounts();

            // Filter normal accounts
            uaccounts = uaccounts.stream().filter(accountx -> accountx.getType() != AccountType.DEVICE)
                    .collect(Collectors.toSet());

            if (uaccounts.isEmpty())
                throw new AuthenticationException("No accounts for user");

            if (uaccounts.size() > 1) {
                // TODO: Need return list and redirect to annother page...
                return ErrorResponse.status(Status.FORBIDDEN,
                        "Multiple Accounts not supported for now !! (open ticket !)");
            }

            AccountAuth token = new AccountAuth(uaccounts.iterator().next().getId(), user.getId());
            //token.setRememberMe(false); // to be remembered across sessions

            currentUser.login(token);

            // currentUser.getSession(true).setTimeout(xxxxx);

            if (currentUser.isAuthenticated()) {
                AccountPrincipal principal = (AccountPrincipal) currentUser.getPrincipal();
                logged = true;
                authtoken = principal.getAccountUUID();
                user.setLastLogin(new Date());
            }

        } catch (UnknownAccountException e) {
            return ErrorResponse.UNAUTHORIZED("Unknown Account");
        } catch (IncorrectCredentialsException e) {
            return ErrorResponse.status(Status.FORBIDDEN, "Incorrect Credentials");
        } catch (AuthenticationException e) {
            return ErrorResponse.UNAUTHORIZED(e.getMessage());
        }
    }

    if (logged) {
        return noCache(Response.status(Status.OK).entity("{\"token\":\"" + authtoken + "\"}"));
    } else {
        return ErrorResponse.UNAUTHORIZED("Authentication Fail");
    }

}

From source file:ca.uhnresearch.pughlab.tracker.security.LdapRealm.java

License:Apache License

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

    if (token instanceof UsernamePasswordToken) {
        log.debug("Attempting to authenticate: {}", token);
        Collection<LdapContext> contexts = getLdapContextsForToken(token);
        return queryContexts(token, contexts);
    } else {//  ww w  .  j  a v a2 s.  c  om
        throw new AuthenticationException("Invalid token type: " + token.toString());
    }
}