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.kingmed.dp.modules.sys.security.SystemAuthorizingRealm.java

License:Apache License

/**
 * ?, //from w  w  w .  ja v a  2 s .c o m
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

    int activeSessionSize = getSystemService().getSessionDAO().getActiveSessions(false).size();
    if (logger.isDebugEnabled()) {
        logger.debug("login submit, active session size: {}, username: {}", activeSessionSize,
                token.getUsername());
    }

    // ??
    if (UserUtils.isValidateCodeLogin(token.getUsername(), false, false)) {
        Session session = UserUtils.getSession();
        String code = (String) session.getAttribute(ValidateCodeServlet.VALIDATE_CODE);
        if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().equals(code)) {
            throw new AuthenticationException("msg:??, ?.");
        }
    }

    // ???
    User user = getSystemService().getUserByLoginName(token.getUsername());
    if (user != null) {
        if (Global.NO.equals(user.getLoginFlag())) {
            throw new AuthenticationException("msg:???.");
        }
        byte[] salt = Encodes.decodeHex(user.getPassword().substring(0, 16));
        return new SimpleAuthenticationInfo(new Principal(user, token.isMobileLogin()),
                user.getPassword().substring(16), ByteSource.Util.bytes(salt), getName());
    } else {
        return null;
    }
}

From source file:com.kingmed.dp.modules.sys.security.SystemAuthorizingRealm.java

License:Apache License

/**
 * ?, ???//w  w  w .  j  ava  2  s . c  o m
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    Principal principal = (Principal) getAvailablePrincipal(principals);
    // ??
    if (!Global.TRUE.equals(Global.getConfig("user.multiAccountLogin"))) {
        Collection<Session> sessions = getSystemService().getSessionDAO().getActiveSessions(true, principal,
                UserUtils.getSession());
        if (sessions.size() > 0) {
            // ?
            if (UserUtils.getSubject().isAuthenticated()) {
                for (Session session : sessions) {
                    getSystemService().getSessionDAO().delete(session);
                }
            }
            // ???????
            else {
                UserUtils.getSubject().logout();
                throw new AuthenticationException("msg:??");
            }
        }
    }
    User user = getSystemService().getUserByLoginName(principal.getLoginName());
    if (user != null) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<Menu> list = UserUtils.getMenuList();
        for (Menu menu : list) {
            if (StringUtils.isNotBlank(menu.getPermission())) {
                // Permission???
                for (String permission : StringUtils.split(menu.getPermission(), ",")) {
                    info.addStringPermission(permission);
                }
            }
        }
        // ??
        info.addStringPermission("user");
        // ?
        for (Role role : user.getRoleList()) {
            info.addRole(role.getEnname());
        }
        // IP
        getSystemService().updateUserLoginInfo(user);
        // 
        LogUtils.saveLog(Servlets.getRequest(), "");
        return info;
    } else {
        return null;
    }
}

From source file:com.mobileman.kuravis.core.services.security.PlatformRealm.java

License:Apache License

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

    UsernamePasswordToken credentials = (UsernamePasswordToken) token;
    String email = credentials.getUsername();
    String password = new String(credentials.getPassword());

    User user = this.userService.findUserByEmail(email);
    if (user == null) {
        throw new UnknownAccountException("Unknown email: " + email);
    }//from   ww w .  java  2  s .c  om

    try {
        if (SecurityUtils.check(password, user.getAccount().getPassword())) {
            DBObject dbUser = this.userService.findDBUserByEmail(email);

            DBObject account = this.userService.findDBUserAccountByEmail(email);
            dbUser.put("account", account);
            SimpleAuthenticationInfo authInfo = new SimpleAuthenticationInfo(dbUser, password, getName());
            return authInfo;
        } else {
            throw new IncorrectCredentialsException();
        }

    } catch (Exception e) {
        throw new AuthenticationException(e);
    }

}

From source file:com.opass.security.SaltAwareJdbcRealm.java

private PasswdSalt getPasswordForUser(String username) {
    PreparedStatement statement = null;
    ResultSet resultSet = null;// w ww. ja va  2s.c o m
    Connection conn = null;
    try {
        conn = dataSource.getConnection();
        statement = conn.prepareStatement(authenticationQuery);
        statement.setString(1, username);

        resultSet = statement.executeQuery();

        boolean hasAccount = resultSet.next();
        if (!hasAccount)
            return null;

        String salt = null;
        String password = resultSet.getString(1);
        if (resultSet.getMetaData().getColumnCount() > 1)
            salt = resultSet.getString(2);

        if (resultSet.next()) {
            throw new AuthenticationException(
                    "More than one user row found for user [" + username + "]. Usernames must be unique.");
        }

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

    } finally {
        JdbcUtils.closeResultSet(resultSet);
        JdbcUtils.closeStatement(statement);
        JdbcUtils.closeConnection(conn);
    }
}

From source file:com.parallax.server.blocklyprop.security.CloudSessionAuthenticationRealm.java

License:Open Source License

/**
 * Retrieves authentication data from an implementation-specific data source
 * (RDBMS, LDAP, etc) for the given authentication token.
 * <p>/*from  w w w .  jav  a2s.  c om*/
 * For most data sources, 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 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
 * Returns an AuthenticationInfo object containing account data resulting
 * from the authentication ONLY if the lookup is successful (i.e. account
 * exists and is valid, etc.)
 *
 * @throws AuthenticationException
 * if there is an error acquiring data or  performing realm-specific
 * authentication logic for the specified token
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    LOG.info("Obtaining authentication info");

    /*  Any leading and/or trailing white space contained in the credentials
     * (password) has been stripped out before it gets here.
     */
    try {
        if (token instanceof OAuthToken) {
            // Principal = email
            // Credentials = authenticator
            LOG.info("Authentication is using OAuth");
            return new SimpleAccount(token.getPrincipal(), token.getCredentials(), "CloudSession");
        } else {
            LOG.info("Authentication is using local login authority");

            // Principal = login
            String principal = (String) token.getPrincipal();

            // Credentials = password
            String credentials = new String((char[]) token.getCredentials());

            LOG.info("Authenticating user '{}'", principal);

            // Thia can throw a NullPointerException
            User user = SecurityServiceImpl.authenticateLocalUserStatic(principal, credentials);

            if (user == null) {
                LOG.info("No exception but user object is null");
                return null;
            }

            LOG.info("User {} is authenticated", principal);

            try {
                return new SimpleAccount(token.getPrincipal(), token.getCredentials(), "CloudSession");
            } catch (Throwable t) {
                LOG.error("Unexpected exception creating account object", t);
            }
        }
        throw new AuthenticationException("Unable to authenticate token");
    } catch (UnknownUserException ex) {
        LOG.warn("Authentication failed. Message: {}", ex.getMessage());
        throw new AuthenticationException(ex.getMessage());
    } catch (UserBlockedException ex) {
        LOG.warn("Blocked user {}", ex);
        throw new AuthenticationException(ex.getMessage());
    } catch (EmailNotConfirmedException ex) {
        LOG.warn("Authentication failed. Message: {}", ex.getMessage());
        throw new AuthenticationException("EmailNotConfirmed");
    } catch (InsufficientBucketTokensException ex) {
        LOG.info("Insufficient bucket tokens: {}", ex.getMessage());
        throw new AuthenticationException(ex.getMessage());
    } catch (NullPointerException npe) {
        LOG.warn("NullPointer", npe);
        throw new AuthenticationException(npe.getMessage());
    } catch (Throwable t) {
        // This is a catchall exception handler that kicks the can back
        // to the caller
        LOG.warn("Throwable", t);
    }

    return null;
}

From source file:com.sonicle.webtop.core.app.shiro.WTFormAuthFilter.java

License:Open Source License

@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
        ServletResponse response) throws Exception {
    WebTopSession webtopSession = SessionContext.getCurrent();
    if (webtopSession != null) {
        String clientId = ServletUtils.getCookie((HttpServletRequest) request, COOKIE_WEBTOP_CLIENTID);
        if (StringUtils.isBlank(clientId)) {
            clientId = IdentifierUtils.getUUIDTimeBased();
            ServletUtils.setCookie((HttpServletResponse) response, COOKIE_WEBTOP_CLIENTID, clientId,
                    60 * 60 * 24 * 365 * 10);
        }//from  w  w w .ja  v  a 2  s.  co  m
        webtopSession.getSession().setAttribute(SessionManager.ATTRIBUTE_WEBTOP_CLIENTID, clientId);

        String location = ServletUtils.getStringParameter(request, "location", null);
        if (location != null) {
            String url = ServletHelper.sanitizeBaseUrl(location);
            webtopSession.getSession().setAttribute(SessionManager.ATTRIBUTE_CLIENT_URL, url);
            logger.trace("[{}] Location: {}", webtopSession.getId(), url);
        }
    }

    WTRealm wtRealm = (WTRealm) ShiroUtils.getRealmByName(WTRealm.NAME);
    if (wtRealm != null) {
        try {
            wtRealm.checkUser((Principal) subject.getPrincipal());
        } catch (WTException ex) {
            logger.error("User check error", ex);
            writeAuthLog((UsernamePasswordDomainToken) token, (HttpServletRequest) request, "LOGIN_FAILURE");
            setFailureAttribute(request, new AuthenticationException(ex));
            return true;
        }
    }

    writeAuthLog((UsernamePasswordDomainToken) token, (HttpServletRequest) request, "LOGIN");
    return super.onLoginSuccess(token, subject, request, response);
}

From source file:com.sonicle.webtop.core.app.shiro.WTRealm.java

License:Open Source License

private Principal authenticateUser(String domainId, String internetDomain, String username, char[] password)
        throws AuthenticationException {
    WebTopApp wta = WebTopApp.getInstance();
    WebTopManager wtMgr = wta.getWebTopManager();
    AuthenticationDomain authAd = null, priAd = null;
    boolean autoCreate = false, impersonate = false;

    try {/*from ww w. ja  va2 s . co  m*/
        DirectoryManager dirManager = DirectoryManager.getManager();

        // Defines authentication domains for the auth phase and for 
        // building the right principal
        logger.debug("Building the authentication domain");
        if (isSysAdmin(internetDomain, username)) {
            impersonate = false;
            authAd = priAd = wtMgr.createSysAdminAuthenticationDomain();

        } else {
            if (wta.isInMaintenance())
                throw new MaintenanceException("Maintenance is active. Only sys-admin can login.");
            ODomain domain = null;
            if (!StringUtils.isBlank(internetDomain)) {
                List<ODomain> domains = wtMgr.listByInternetDomain(internetDomain);
                if (domains.isEmpty())
                    throw new WTException("No enabled domains match specified internet domain [{}]",
                            internetDomain);
                if (domains.size() != 1)
                    throw new WTException("Multiple domains match specified internet domain [{}]",
                            internetDomain);
                domain = domains.get(0);
            } else {
                domain = wtMgr.getDomain(domainId);
                if ((domain == null) || !domain.getEnabled())
                    throw new WTException("Domain not found [{}]", domainId);
            }

            if (isSysAdminImpersonate(username)) {
                impersonate = true;
                authAd = wtMgr.createSysAdminAuthenticationDomain();
                priAd = wtMgr.createAuthenticationDomain(domain);
            } else if (isDomainAdminImpersonate(username)) {
                impersonate = true;
                authAd = priAd = wtMgr.createAuthenticationDomain(domain);
            } else {
                impersonate = false;
                authAd = priAd = wtMgr.createAuthenticationDomain(domain);
            }
            autoCreate = domain.getUserAutoCreation();
        }

        DirectoryOptions opts = wta.createDirectoryOptions(authAd);
        AbstractDirectory directory = dirManager.getDirectory(authAd.getDirUri().getScheme());
        if (directory == null)
            throw new WTException("Directory not supported [{}]", authAd.getDirUri().getScheme());

        // Prepare principal for authentication
        String authUsername = impersonate ? "admin" : directory.sanitizeUsername(opts, username);
        Principal authPrincipal = new Principal(authAd, impersonate, authAd.getDomainId(), authUsername,
                password);
        logger.debug("Authenticating principal [{}, {}]", authPrincipal.getDomainId(),
                authPrincipal.getUserId());
        AuthUser userEntry = directory.authenticate(opts, authPrincipal);

        // Authentication phase passed succesfully, now build the right principal!
        Principal principal = null;
        if (impersonate) {
            String impUsername = sanitizeImpersonateUsername(username);
            principal = new Principal(priAd, impersonate, priAd.getDomainId(), impUsername, password);

            UserProfileId pid = new UserProfileId(principal.getDomainId(), principal.getUserId());
            OUser ouser = wta.getWebTopManager().getUser(pid);
            // We cannot continue if the user is not present, impersonation needs it!
            if (ouser == null)
                throw new WTException("User not found [{}]", pid.toString());
            principal.setDisplayName(ouser.getDisplayName());

        } else {
            // Authentication result points to the right userId...
            principal = new Principal(priAd, impersonate, priAd.getDomainId(), userEntry.userId, password);
            principal.setDisplayName(StringUtils.defaultIfBlank(userEntry.displayName, userEntry.userId));
        }

        if (autoCreate)
            principal.pushDirectoryEntry(userEntry);
        return principal;

    } catch (URISyntaxException | WTException | DirectoryException ex) {
        logger.error("Authentication error", ex);
        throw new AuthenticationException(ex);
    }
}

From source file:com.stormpath.shiro.realm.PassthroughApplicationRealm.java

License:Apache License

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

    AccountAuthenticationToken accessAuthToken = (AccountAuthenticationToken) token;

    PrincipalCollection principals;//from   w ww.ja  v  a  2  s. co m

    try {

        Account account = accessAuthToken.getAccount();
        // we should not reach this point if the account is not enabled, but, just in case.
        if (AccountStatus.ENABLED != account.getStatus()) {
            throw new AuthenticationException("Account for user [" + account.getHref() + "] is not enabled.");
        }

        principals = createPrincipals(account);
    } catch (Exception e) {
        throw new AuthenticationException("Unable to obtain authenticated account properties.", e);
    }

    return new SimpleAuthenticationInfo(principals, null);
}

From source file:com.streamreduce.core.service.InventoryServiceImplTest.java

License:Apache License

@Before
public void setUp() throws Exception {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String feb282012TimeStamp = Long.toString(sdf.parse("2012-02-28").getTime());
    User sampleUser = new User.Builder().account(new Account.Builder().name("ABC").build())
            .username("sampleUser").build();
    sampleFeedConnection = new Connection.Builder().provider(ConnectionProvidersForTests.RSS_PROVIDER)
            .url(SAMPLE_FEED_FILE_PATH).alias("EC2").user(sampleUser).authType(AuthType.NONE).build();
    Map<String, String> metadata = new HashMap<>();

    metadata.put("last_activity_poll", feb282012TimeStamp);

    sampleFeedConnection.setMetadata(metadata);
    sampleFeedConnection.setId(new ObjectId());

    inventoryService = new InventoryServiceImpl();

    ConnectionProviderFactory cpf = mock(ConnectionProviderFactory.class);
    when(cpf.externalIntegrationConnectionProviderFromId(sampleFeedConnection.getProviderId()))
            .thenReturn(ConnectionProvidersForTests.RSS_PROVIDER);
    ReflectionTestUtils.setField(inventoryService, "connectionProviderFactory", cpf);

    SecurityService ssMock = Mockito.mock(SecurityService.class);
    EventDAO edMock = Mockito.mock(EventDAO.class);
    EventServiceImpl esImpl = new EventServiceImpl();

    // Return null for the current user
    Mockito.when(ssMock.getCurrentUser()).thenThrow(new AuthenticationException("A user must be logged in!"));

    // Use reflection to set the EventDAO in EventServiceImpl
    ReflectionTestUtils.setField(esImpl, "eventDAO", edMock);

    mockMessageService = mock(MessageService.class);
}

From source file:com.streamreduce.core.service.SecurityServiceImpl.java

License:Apache License

@Override
public Connection getCurrentGatewayConnection() {
    final String apiKey = (String) SecurityUtils.getSubject().getPrincipal();
    if (apiKey != null) {
        return getByApiKey(apiKey, GatewayProvider.TYPE);
    } else {/*from w w  w. j  av a 2 s  .  com*/
        throw new AuthenticationException("A gateway connection must be logged in!");
    }
}