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:edu.usu.sdl.openstorefront.security.HeaderRealm.java

License:Apache License

private HeaderAccount populateAccount(HeaderAuthToken headerAuthToken) {
    HeaderAccount headerAccount = new HeaderAccount();

    UserContext userContext = headerAuthToken.getUserContext();
    boolean admin = false;
    if (userContext == null) {
        ServiceProxy serviceProxy = new ServiceProxy();

        if (StringUtils.isBlank(headerAuthToken.getUsername())) {
            //They shouldn't get here unless open am is not configured
            throw new AuthenticationException("Unable to login.  No credentials passed.  Auth filter not set.");
        }/*from w  w  w.  j  ava2 s .  com*/

        UserProfile userProfile = new UserProfile();
        userProfile.setUsername(headerAuthToken.getUsername());
        userProfile.setFirstName(headerAuthToken.getFirstname());
        userProfile.setLastName(headerAuthToken.getLastname());
        userProfile.setOrganization(headerAuthToken.getOrganization());
        userProfile.setEmail(headerAuthToken.getEmail());
        userProfile.setExternalGuid(headerAuthToken.getGuid());

        if (StringUtils.isNotBlank(headerAuthToken.getGroup())
                && StringUtils.isNotBlank(headerAuthToken.getAdminGroupName())) {
            admin = headerAuthToken.getGroup().contains(headerAuthToken.getAdminGroupName());
        }
        userContext = serviceProxy.getUserService().handleLogin(userProfile, headerAuthToken.getRequest(),
                admin);
    } else {
        admin = userContext.isAdmin();
    }
    headerAccount.setCredentials(userContext);
    headerAccount.getSimplePrincipals().add(userContext, "Open Am Header User");
    if (admin) {
        headerAccount.getRoles().add(SecurityUtil.ADMIN_ROLE);
    }

    return headerAccount;
}

From source file:edu.wisc.nexus.auth.rut.realm.RemoteUserTokenAuthenticatingRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("doGetAuthenticationInfo(" + token + "), principal=" + token.getPrincipal()
                + ", credentials=" + token.getCredentials());
    }//from w  ww.  j av a 2  s  . c o  m

    // Handle REMOTE_USER auth first
    if (RemoteUserAuthenticationToken.class.isAssignableFrom(token.getClass())) {
        final String remoteUser = ((RemoteUserAuthenticationToken) token).getRemoteUser();
        if (remoteUser == null) {
            throw new AuthenticationException(RemoteUserAuthenticationToken.class.getSimpleName()
                    + " provided but no remoteUser value is set");
        }

        if (!this.userDao.userExists(remoteUser)) {
            //Create the missing remote_user in the DAO
            this.userDao.createUser(remoteUser);
        }

        logger.debug("Returning RemoteUserAuthenticationInfo for {}", remoteUser);
        return new RemoteUserAuthenticationInfo(remoteUser, getName());
    }

    // Handle token auth second
    if (UsernamePasswordToken.class.isAssignableFrom(token.getClass())) {
        final String userId = ((UsernamePasswordToken) token).getUsername();
        final String password = this.userDao.getUserPasswordToken(userId);
        if (password == null) {
            return null;
        }

        logger.debug("Returning SimpleAuthenticationInfo for {}", userId);
        return new SimpleAuthenticationInfo(userId, password, getName());
    }

    // Neither REMOTE_USER or token auth
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Token '" + token.getClass() + "' is not assignable to: "
                + UsernamePasswordToken.class + " or " + RemoteUserAuthenticationToken.class);
    }
    return null;
}

From source file:eu.forgestore.ws.util.ShiroUTAuthorizingRealm.java

License:Apache License

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

    logger.info("AuthenticationToken at=" + at.toString());

    UsernamePasswordToken token = (UsernamePasswordToken) at;
    logger.info("tokengetUsername at=" + token.getUsername());
    //logger.info("tokengetPassword at=" + String.valueOf(token.getPassword()));
    //logger.info("tokengetPrincipal at=" + token.getPrincipal());

    FStoreUser bu = fstoreRepositoryRef.getUserByUsername(token.getUsername());
    if (bu == null) {
        throw new AuthenticationException("Sorry! No login for you.");
    }//from   w  ww . j  av  a  2 s.c  o m

    String originalPass = bu.passwordValue();
    String suppliedPass = EncryptionUtil.hash(String.valueOf(token.getPassword()));
    logger.info("originalPass =" + originalPass);
    logger.info("suppliedPass =" + suppliedPass);
    if (originalPass.equals(suppliedPass)) {
        logger.info("======= USER is AUTHENTICATED OK =======");
    } else {
        throw new AuthenticationException("Sorry! No login for you.");
    }

    // try {
    // currentUser.login(token);
    // } catch (AuthenticationException ex) {
    // logger.info(ex.getMessage(), ex);
    // throw new AuthenticationException("Sorry! No login for you.");
    // }
    // // Perform authorization check
    // if (!requiredRoles.isEmpty() && !currentUser.hasAllRoles(requiredRoles)) {
    // logger.info("Authorization failed for authenticated user");
    // throw new AuthenticationException("Sorry! No login for you.");
    // }

    SimpleAuthenticationInfo sa = new SimpleAuthenticationInfo();
    sa.setCredentials(token.getCredentials());
    SimplePrincipalCollection principals = new org.apache.shiro.subject.SimplePrincipalCollection();
    principals.add(token.getPrincipal(), "bakerrealm");

    sa.setPrincipals(principals);
    return sa;
}

From source file:gr.upatras.ece.nam.baker.util.ShiroUTAuthorizingRealm.java

License:Apache License

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

    logger.info("AuthenticationToken at=" + at.toString());

    UsernamePasswordToken token = (UsernamePasswordToken) at;
    logger.info("tokengetUsername at=" + token.getUsername());
    //logger.info("tokengetPassword at=" + String.valueOf(token.getPassword()));
    //logger.info("tokengetPrincipal at=" + token.getPrincipal());

    BakerUser bu = bakerRepositoryRef.getUserByUsername(token.getUsername());
    if (bu == null) {
        throw new AuthenticationException("Sorry! No login for you.");
    }//  www. j a v  a2s  . com

    String originalPass = bu.getPassword();
    String suppliedPass = EncryptionUtil.hash(String.valueOf(token.getPassword()));
    logger.info("originalPass =" + originalPass);
    logger.info("suppliedPass =" + suppliedPass);
    if (originalPass.equals(suppliedPass)) {
        logger.info("======= USER is AUTHENTICATED OK =======");
    } else {
        throw new AuthenticationException("Sorry! No login for you.");
    }

    // try {
    // currentUser.login(token);
    // } catch (AuthenticationException ex) {
    // logger.info(ex.getMessage(), ex);
    // throw new AuthenticationException("Sorry! No login for you.");
    // }
    // // Perform authorization check
    // if (!requiredRoles.isEmpty() && !currentUser.hasAllRoles(requiredRoles)) {
    // logger.info("Authorization failed for authenticated user");
    // throw new AuthenticationException("Sorry! No login for you.");
    // }

    SimpleAuthenticationInfo sa = new SimpleAuthenticationInfo();
    sa.setCredentials(token.getCredentials());
    SimplePrincipalCollection principals = new org.apache.shiro.subject.SimplePrincipalCollection();
    principals.add(token.getPrincipal(), "bakerrealm");

    sa.setPrincipals(principals);
    return sa;
}

From source file:io.bootique.shiro.ShiroModuleIT.java

License:Apache License

protected Realm mockRealm() {
    Realm mockRealm = mock(Realm.class);
    when(mockRealm.getName()).thenReturn("TestRealm");
    when(mockRealm.supports(any(AuthenticationToken.class))).then(invocation -> {
        AuthenticationToken token = invocation.getArgument(0);
        return token instanceof UsernamePasswordToken;
    });/*w w w .  j  a  v  a  2  s .c  o  m*/

    when(mockRealm.getAuthenticationInfo(any(AuthenticationToken.class))).then(invocation -> {

        UsernamePasswordToken token = invocation.getArgument(0);
        if (!"password".equals(new String(token.getPassword()))) {
            throw new AuthenticationException("Bad password");
        }

        return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), "TestRealm");
    });

    return mockRealm;
}

From source file:io.buji.pac4j.ClientRealm.java

License:Apache License

/**
 * Authenticates a user and retrieves its user profile.
 *
 * @param authenticationToken/* w  ww . j  a v  a 2  s  . c o  m*/
 *            the authentication token
 * @throws AuthenticationException
 *             if there is an error during authentication.
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken authenticationToken)
        throws AuthenticationException {
    try {
        return internalGetAuthenticationInfo(authenticationToken);
    } catch (final TechnicalException e) {
        throw new AuthenticationException(e);
    }
}

From source file:io.starter.security.JdbcRealm.java

License:Apache License

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

    String[] result;/*w  ww.  ja  va2s  .  co  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 {
        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:juzu.plugin.shiro.impl.ShiroAuthenticator.java

License:Open Source License

public Response doLogin(Stage.Handler stage) {
    Request request = stage.getRequest();
    Login loginAnnotation = request.getHandler().getMethod().getAnnotation(Login.class);
    Subject subject = SecurityUtils.getSubject();

    boolean remember = request.getParameterArguments().get(loginAnnotation.rememberMe()) != null ? true : false;
    String username = null;/*from w ww  .  j a v a2 s  .  co  m*/
    String password = null;
    try {
        username = request.getParameterArguments().get(loginAnnotation.username()).getValue();
        password = request.getParameterArguments().get(loginAnnotation.password()).getValue();
    } catch (NullPointerException e) {
        List<ControlParameter> parameters = request.getHandler().getParameters();
        for (ControlParameter parameter : parameters) {
            if (parameter instanceof ContextualParameter) {
                if (AuthenticationException.class.isAssignableFrom(parameter.getType())) {
                    request.getContextualArguments().put((ContextualParameter) parameter,
                            new AuthenticationException(e.getCause()));
                    return stage.invoke();
                }
            }
        }

        //
        return new Response.Error(e);
    }

    try {
        subject.login(new UsernamePasswordToken(username, password.toCharArray(), remember));

        //
        Response resp = stage.invoke();
        if (remember && rememberMeSupported) {
            RememberMeUtil.forgetIdentity();
            RememberMeUtil.rememberSerialized();
        }
        return resp;
    } catch (AuthenticationException e) {
        List<ControlParameter> parameters = request.getHandler().getParameters();
        for (ControlParameter parameter : parameters) {
            if (parameter instanceof ContextualParameter) {
                if (AuthenticationException.class.isAssignableFrom(parameter.getType())) {
                    request.getContextualArguments().put((ContextualParameter) parameter, e);
                    Response resp = stage.invoke();
                    if (remember) {
                        RememberMeUtil.forgetIdentity();
                    }
                    return resp;
                }
            }
        }

        return new Response.Error(e);
    }
}

From source file:myStuff.rest.shiro.MyRealm.java

License:Apache License

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
    String username = (String) principal.getPrimaryPrincipal();
    if (username.equals("root")) {
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        return new SimpleAuthorizationInfo(roles);
    }/*from   w w  w  .j a  va2s.co  m*/
    throw new AuthenticationException("Unknown user");
}

From source file:no.priv.bang.ukelonn.web.security.dbrealm.UkelonnRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
    if (!(token instanceof UsernamePasswordToken)) {
        throw new AuthenticationException("UkelonnRealm shiro realm only accepts UsernamePasswordToken");
    }/*from   w ww . j  a  v a  2s .c  om*/

    UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
    Object principal = usernamePasswordToken.getPrincipal();
    String username = usernamePasswordToken.getUsername();
    try {
        try (PreparedStatement statement = database.prepareStatement("select * from users where username=?")) {
            statement.setString(1, username);
            ResultSet passwordResultSet = database.query(statement);
            if (passwordResultSet == null) {
                throw new AuthenticationException(
                        "UkelonnRealm shiro realm failed to get passwords from the database");
            }

            if (passwordResultSet.next()) {
                String password = passwordResultSet.getString("password");
                String salt = passwordResultSet.getString("salt");
                ByteSource decodedSalt = Util.bytes(Base64.getDecoder().decode(salt));
                return new SimpleAuthenticationInfo(principal, password, decodedSalt, getName());
            } else {
                throw new IncorrectCredentialsException("Username \"" + username + "\" not found");
            }
        }
    } catch (SQLException e) {
        throw new AuthenticationException(
                "UkelonnRealm shiro realm got SQL error exploring the password results", e);
    }
}