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:cn.com.rexen.ext.shiro.web.filter.authc.ForwardedX509AuthenticationFilter.java

License:Open Source License

@Override
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
    HttpServletRequest httpRequest = (HttpServletRequest) request;

    if (!useCertificate && !useSubjectDN && !useIssuerDN && !useSerialNumber) {
        throw new AuthenticationException(
                "ForwardedX509AuthenticationFilter is set up to use no forwarded header, you certainly missed a configuration step");
    }// w w  w.  j  av a 2  s  .  c  o m

    if (false) {
        // FIXME Decide what to do with the -Verify header
        String verifiedHeader = httpRequest.getHeader(SSL_CLIENT_VERIFY);
        if (!verifiedHeader.isEmpty()) {
            if (!"SUCCESS".equals(verifiedHeader)) {
                throw new AuthenticationException("Client certificate verification failure was forwarded");
            }
        }
    }

    if (useCertificate) {

        X509Certificate[] certificateChain = null;

        String certHeader = httpRequest.getHeader(SSL_CLIENT_CERT);
        if (notEmpty(certHeader)) {
            certificateChain = readX509CertificateChainFromPEM(rebuildPEMBundleFromHttpHeader(certHeader));
        }

        if (certificateChain == null) {
            throw new AuthenticationException(
                    "Set up to use " + SSL_CLIENT_CERT + " header but it was either empty or unparseable");
        }

        return new X509AuthenticationToken(certificateChain, getHost(request));

    }

    X500Principal subjectDN = null;
    X500Principal issuerDN = null;
    String hexSerialNumber = null;

    if (useSubjectDN) {
        String subjectDNHeader = httpRequest.getHeader(SSL_CLIENT_S_DN);
        if (notEmpty(subjectDNHeader)) {
            subjectDN = readX500PrincipalFromString(subjectDNHeader);
        }
    }

    if (useIssuerDN) {
        String issuerDNHeader = httpRequest.getHeader(SSL_CLIENT_I_DN);
        if (notEmpty(issuerDNHeader)) {
            issuerDN = readX500PrincipalFromString(issuerDNHeader);
        }
    }

    if (useSerialNumber) {
        String serialHeader = httpRequest.getHeader(SSL_CLIENT_M_SERIAL);
        if (notEmpty(serialHeader)) {
            hexSerialNumber = readHexSerialNumberFromString(serialHeader);
        }
    }

    if (subjectDN == null && issuerDN == null && isEmpty(hexSerialNumber)) {
        throw new AuthenticationException("All set up forwarded headers were empty");
    }

    return new X509AuthenticationToken(subjectDN, issuerDN, hexSerialNumber, getHost(request));
}

From source file:cn.evilcoder.fantasyblog4j.shiro.ShiroDbRealm.java

License:Apache License

/**
 * ?,.//from  w w  w .  ja va2 s  .  co m
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

    String username = String.valueOf(token.getPrincipal());
    String password = new String((char[]) token.getCredentials());

    User user = userService.selectByUsername(username);
    if (user == null) {
        throw new AuthenticationException("???.");
    }
    if (!userService.checkPassword(user, password)) {
        throw new AuthenticationException("???.");
    }

    return new SimpleAuthenticationInfo(username, password, getName());
}

From source file:com.app.shiro.SaltedJdbcRealm.java

License:Open Source License

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

    UsernamePasswordToken userPassToken = (UsernamePasswordToken) token;

    final String emailAddress = userPassToken.getUsername();

    if (ValidatorUtil.isNull(emailAddress)) {
        _log.error("Email address is null");

        return null;
    }//from w ww . ja  va  2s . c om

    try {
        User user = UserUtil.getUserByEmailAddress(emailAddress);

        if (user == null) {
            _log.error("No account found for emailAddress: {}", emailAddress);

            return null;
        }

        return new UserSaltedAuthenticationInfo(emailAddress, user.getPassword(), user.getSalt());
    } catch (Exception e) {
        throw new AuthenticationException(e);
    }
}

From source file:com.axelor.auth.AuthLdap.java

License:Open Source License

@Transactional
public boolean login(String user, String password) throws AuthenticationException {
    if (!this.isEnabled()) {
        throw new IllegalStateException("LDAP is not enabled.");
    }//from   w w w .  j  a v  a 2  s . c  om
    try {
        return doLogin(user, password);
    } catch (NamingException e) {
        throw new AuthenticationException(e);
    }
}

From source file:com.blazarquant.bfp.core.security.config.DatabaseUserRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
        throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
    UserDetails userDetails = userDAO.findUserByLogin(token.getUsername());
    if (userDetails != null) {
        return new SimpleAuthenticationInfo(userDetails, userDetails.getPassword(), getName());
    } else {// w w w  . j  a  va2s.com
        throw new AuthenticationException(
                "Failed to find user " + ((UsernamePasswordToken) authenticationToken).getUsername());
    }
}

From source file:com.caricah.iotracah.core.handlers.RequestHandler.java

License:Apache License

public Observable<IOTClient> checkPermission(String sessionId, String authKey, AuthorityRole role,
        List<String> topicList) {

    return Observable.create(observable -> {

        IotClientKey clientKey = new IotClientKey();
        clientKey.setSessionId(sessionId);

        Subject subject = new Subject.Builder().sessionId(clientKey).buildSubject();

        final IOTClient session = (IOTClient) subject.getSession(false);

        if (session != null && subject.isAuthenticated()) {

            try {

                if (!AuthorityRole.CONNECT.equals(role)) {

                    if (Protocol.fromString(session.getProtocol()).isNotPersistent()) {

                        String session_auth_key = session.getAuthKey();

                        /**
                         * Make sure for non persistent connections the authKey matches
                         * the stored authKey. Otherwise fail the request.
                         *//*from  w  w w  .  j  av a2 s .c  o  m*/
                        if (!StringUtils.isEmpty(session_auth_key)) {
                            if (!session_auth_key.equals(authKey))
                                throw new UnauthenticatedException("Client fails auth key assertion.");

                        }
                    }

                    List<Permission> permissions = topicList.stream()
                            .map(topic -> getPermission(session.getPartitionId(), session.getUsername(),
                                    session.getClientIdentification(), role, topic))
                            .collect(Collectors.toList());

                    subject.checkPermissions(permissions);
                }

                //Update session last accessed time.
                session.touch();

                observable.onNext(session);
                observable.onCompleted();

            } catch (AuthorizationException e) {
                //Notify failure to authorize user.
                observable.onError(e);
            }

        } else {
            observable.onError(new AuthenticationException(
                    "Client must be authenticated {Try connecting first} found : " + session));
        }

    });

}

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

License:Apache License

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

    PreparedStatement ps = null;//w  w  w  .  jav a  2s.  c  om
    ResultSet rs = null;
    String password = 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.");
            }

            password = rs.getString(1);

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

    return password;
}

From source file:com.funtl.framework.smoke.core.modules.sys.security.SystemAuthorizingRealm.java

License:Apache License

/**
 * ?, //from   w  w w.  j a v a2 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 (LoginController.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.funtl.framework.smoke.core.modules.sys.security.SystemAuthorizingRealm.java

License:Apache License

/**
 * ?, ???/* w w  w. jav  a2s  .  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.gfan.dp.framework.shiro.ShiroDbRealm.java

License:Apache License

/**
 * ?,.//from   w  ww  . j  ava  2  s  . c o  m
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    ShiroGfanCookieToken token = (ShiroGfanCookieToken) authcToken;
    String tokenString = token.getToken();
    User user = null;
    try {
        user = webUserService.verify("coop", tokenString);
    } catch (LogicException e) {
        throw new AuthenticationException(e);
    }
    if (user == null) {
        return null;
    }
    // 
    doSomeAction(user);
    return new SimpleAuthenticationInfo(user, null, getName());
}