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:org.sonatype.security.realms.ldap.realms.LdapRealm.java

License:Open Source License

@Override
protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token,
        LdapContextFactory ldapContextFactory) throws NamingException {
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    String username = upToken.getUsername();
    String pass = String.valueOf(upToken.getPassword());

    // Verify non-empty password
    if (Strings.isNullOrEmpty(pass)) {
        throw new AuthenticationException("Password must not be empty");
    }//from w w w  . ja  va2s  .  c om

    try {
        this.ldapManager.authenticateUser(username, pass);
        // creating AuthInfo with plain pass (relates to creds matcher too)
        return new SimpleAuthenticationInfo(username, pass.toCharArray(), getName());
    } catch (org.sonatype.security.authentication.AuthenticationException e) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("User: " + username + " could not be authenticated ", e);
        }
        throw new org.apache.shiro.authc.AuthenticationException(e.getMessage());
    }
}

From source file:org.sonatype.security.realms.MemoryAuthenticationOnlyRealm.java

License:Open Source License

/**
 * This method is where the authentication is controlled.  You will receive a
 * token, from which you can retrieve the username.  Then you can lookup in your
 * storage, the credentials for that user, place those in an AuthenticationInfo
 * object and return it, the credential matcher will handle comparing them.
 * /*  w ww.j  av a2 s . c o  m*/
 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
    if (!UsernamePasswordToken.class.isAssignableFrom(arg0.getClass())) {
        return null;
    }

    String username = ((UsernamePasswordToken) arg0).getUsername();

    String password = authenticationMap.get(username);

    if (password == null) {
        throw new AuthenticationException("Invalid username '" + username + "'");
    }

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

From source file:org.sonatype.security.realms.simple.SimpleRealm.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    // all we need to do here is look up the user by id, in the user store, and return a AuthenticationInfo with the
    // real users id and pass.

    // type check the token
    if (!UsernamePasswordToken.class.isAssignableFrom(token.getClass())) {
        return null;
    }//from   w  w w  .j  ava  2 s  . c o m
    String userId = ((UsernamePasswordToken) token).getUsername();

    // look the user in the example user store
    SimpleUser user = this.userStore.getUser(userId);

    if (user == null) {
        throw new AuthenticationException("Invalid username '" + userId + "'");
    }

    return new SimpleAuthenticationInfo(user.getUserId(), user.getPassword(), getName());
}

From source file:org.usergrid.security.shiro.Realm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    PrincipalCredentialsToken pcToken = (PrincipalCredentialsToken) token;

    if (pcToken.getCredentials() == null) {
        throw new CredentialsException("Missing credentials");
    }/*from w  ww.  ja  v a2 s .  com*/

    boolean authenticated = false;

    PrincipalIdentifier principal = pcToken.getPrincipal();
    PrincipalCredentials credentials = pcToken.getCredentials();

    if (credentials instanceof ClientCredentials) {
        authenticated = true;
    } else if ((principal instanceof AdminUserPrincipal) && (credentials instanceof AdminUserPassword)) {
        authenticated = true;
    } else if ((principal instanceof AdminUserPrincipal) && (credentials instanceof AdminUserAccessToken)) {
        authenticated = true;
    } else if ((principal instanceof ApplicationUserPrincipal)
            && (credentials instanceof ApplicationUserAccessToken)) {
        authenticated = true;
    } else if ((principal instanceof ApplicationPrincipal) && (credentials instanceof ApplicationAccessToken)) {
        authenticated = true;
    } else if ((principal instanceof OrganizationPrincipal)
            && (credentials instanceof OrganizationAccessToken)) {
        authenticated = true;
    }

    if (principal != null) {
        if (!principal.isActivated()) {
            throw new AuthenticationException("Unactivated identity");
        }
        if (principal.isDisabled()) {
            throw new AuthenticationException("Disabled identity");
        }
    }

    if (!authenticated) {
        throw new AuthenticationException("Unable to authenticate");
    }

    logger.debug("Authenticated: {}", principal);

    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(pcToken.getPrincipal(),
            pcToken.getCredentials(), getName());
    return info;
}

From source file:pe.gob.sunat.tecnologia3.arquitectura.framework.desktop.seguridad.realm.OAuth2Realm.java

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    OAuth2Token facebookToken = (OAuth2Token) token;

    if (facebookToken.getAuthCode() != null && facebookToken.getAuthCode().trim().length() > 0) {
        URL authUrl;//from w w  w. ja va2 s  .  com
        try {

            StringBuffer redirectUri = new StringBuffer();
            redirectUri.append("https://graph.facebook.com/oauth/access_token?client_id=");
            redirectUri.append(APP_ID);
            redirectUri.append("&client_secret=").append(APP_SECRET);
            redirectUri.append("&grant_type=client_credentials");
            redirectUri.append("&redirect_uri=https://graph.facebook.com/oauth/access_token?client_id=");
            redirectUri.append(APP_ID);
            redirectUri.append("&client_secret=").append(APP_SECRET);
            redirectUri.append("&redirect_uri=##facebook.oauth.callback##&client_secret=");
            redirectUri.append(APP_SECRET);
            redirectUri.append("&code=").append(facebookToken.getAuthCode());

            authUrl = new URL(redirectUri.toString());

            String authResponse = readURL(authUrl);
            logger.log(Level.INFO, authResponse);
            String accessToken = getPropsMap(authResponse).get("access_token");
            logger.log(Level.INFO, " Token de acceso..." + accessToken);
            //                URL url = new URL("https://graph.facebook.com/"+APP_ID+"?access_token=" + accessToken);
            //                String fbResponse = readURL(url);
            //                FacebookUserDetails fud = new FacebookUserDetails(fbResponse);
            //                return new FacebookAuthenticationInfo(fud, this.getName());
            if (StringUtils.isNotBlank(accessToken)) {
                userdao.insertarUsuario(new Usuario());
            }
            return null;
        } catch (Throwable e1) {
            e1.printStackTrace();
            throw new AuthenticationException(e1);
        }
    }
    return null;
}

From source file:portal.api.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());

    PortalUser bu = portalRepositoryRef.getUserByUsername(token.getUsername());
    if (bu == null) {
        throw new AuthenticationException("Sorry! No login for you.");
    }/* ww w. j  av  a 2  s. co m*/

    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(), "portalrealm");

    sa.setPrincipals(principals);
    return sa;
}

From source file:streamflow.server.security.DatastoreRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    // Make sure the token is of the property type
    if (!(token instanceof UsernamePasswordToken)) {
        //LOG.error("The provided token is not a UsernamePasswordToken");

        throw new AuthenticationException("The provided token is not a UsernamePasswordToken");
    }/*  ww  w . ja  va2 s .co  m*/

    // Retrieve the username from the token
    UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
    String username = usernamePasswordToken.getUsername();

    if (username == null) {
        //LOG.error("The provided token does not contain a username");

        throw new AuthenticationException("The provided token does not contain a username");
    }

    User user = getUserByUsernameOrEmail(username);
    if (user == null) {
        LOG.warn("User with the specified username does not exist: " + username);

        throw new AuthenticationException("The username/password was invalid");
    }

    // Make sure the user account is enabled
    if (!user.getEnabled()) {
        //LOG.error("User account with the specified username is disabled: {}", username);

        throw new AuthenticationException("The user account is disabled");
    }

    // Generate the authentication info using the passsword and salt
    SimpleAccount info = new SimpleAccount(username, user.getPassword(),
            new SimpleByteSource(user.getPasswordSalt()), getName());

    // Associate the principals with the authentication info
    SimplePrincipalCollection principals = new SimplePrincipalCollection();
    principals.add(user.getId(), getName());
    principals.add(user.getUsername(), getName());
    principals.add(user.getEmail(), getName());
    info.setPrincipals(principals);

    return info;
}

From source file:stroom.security.server.AuthenticationServiceImpl.java

License:Apache License

/**
 * @param userName/*from   ww  w.  ja  va 2 s .c  om*/
 * @param password
 * @return
 */
@Override
@Insecure
public User login(final String userName, final String password) {
    User user = null;

    if (userName == null || userName.length() == 0) {
        loginFailure(userName, new AuthenticationException("No user name"));

    } else {
        try {
            final HttpServletRequest request = httpServletRequestHolder.get();

            // Create the authentication token from the user name and
            // password
            final UsernamePasswordToken token = new UsernamePasswordToken(userName, password, true,
                    request.getRemoteHost());

            // Attempt authentication
            final Subject currentUser = SecurityUtils.getSubject();
            currentUser.login(token);

            user = (User) currentUser.getPrincipal();

            // Pass back the user info
            user = handleLogin(request, user, userName);

            // Audit the successful logon
            eventLog.logon(user.getName());

        } catch (final RuntimeException e) {
            loginFailure(userName, e);
        }
    }

    // Pass back the user info
    return user;
}

From source file:stroom.security.server.DBRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token)
        throws AuthenticationException {
    if (token instanceof JWTAuthenticationToken) {
        final JWTAuthenticationToken jwtAuthenticationToken = (JWTAuthenticationToken) token;
        return authenticateWithJWT(jwtAuthenticationToken);
    }/*from  w ww .  j ava  2s . com*/

    if (token instanceof CertificateAuthenticationToken) {
        final CertificateAuthenticationToken certificateAuthenticationToken = (CertificateAuthenticationToken) token;
        return authenticateWithCertificate(certificateAuthenticationToken);
    }

    if (token instanceof UsernamePasswordToken) {
        final UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        return authenticateWithUsernamePassword(usernamePasswordToken);
    }

    throw new AuthenticationException("Token type '" + token.getClass().getSimpleName() + "' is not supported");
}

From source file:stroom.security.server.JWTAuthenticationFilter.java

License:Apache License

public JWTAuthenticationToken createToken(String token) {
    try {/*from w  ww . jav  a2  s .  co m*/
        String subject = null;
        if (token != null) {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SecurityContextImpl.SECRET))
                    .withIssuer(SecurityContextImpl.ISSUER).build();
            DecodedJWT jwt = verifier.verify(token);
            subject = jwt.getSubject();
        }

        return new JWTAuthenticationToken(subject, token);

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