Example usage for org.apache.shiro.authc SimpleAccount SimpleAccount

List of usage examples for org.apache.shiro.authc SimpleAccount SimpleAccount

Introduction

In this page you can find the example usage for org.apache.shiro.authc SimpleAccount SimpleAccount.

Prototype

public SimpleAccount(PrincipalCollection principals, Object credentials, Set<String> roles) 

Source Link

Document

Constructs a SimpleAccount instance for the specified principals and credentials, with the assigned roles.

Usage

From source file:com.enioka.jqm.webui.shiro.JpaRealm.java

License:Open Source License

private SimpleAccount getUser(String login) {
    EntityManager em = null;/*w w  w  .  j  av  a 2 s  .  c o m*/
    try {
        em = Helpers.getEm();
        RUser user = em.createQuery("SELECT u FROM RUser u WHERE UPPER(u.login) = UPPER(:l)", RUser.class)
                .setParameter("l", login).getSingleResult();

        // Credential is a password - in token, it is as a char array
        SimpleAccount res = new SimpleAccount(user.getLogin(), user.getPassword(), getName());

        if (user.getExpirationDate() != null) {
            res.setCredentialsExpired(user.getExpirationDate().before(Calendar.getInstance()));
        } else {
            // No limit = never expires
            res.setCredentialsExpired(false);
        }
        if (user.getHashSalt() != null) {
            res.setCredentialsSalt(ByteSource.Util.bytes(Hex.decode(user.getHashSalt())));
        } else {
            res.setCredentialsSalt(null);
        }
        res.setLocked(user.getLocked());

        // Roles
        for (RRole r : user.getRoles()) {
            res.addRole(r.getName());
            for (RPermission p : r.getPermissions()) {
                res.addStringPermission(p.getName());
            }
        }
        return res;
    } catch (NoResultException e) {
        // No such user in realm
        return null;
    } catch (RuntimeException e) {
        e.printStackTrace();
        throw e;
    } finally {
        em.close();
    }
}

From source file:com.freedomotic.security.PluginRealm.java

License:Open Source License

public void addPlugin(String pluginName, String permissions) {
    SimpleAccount pluginUser = new SimpleAccount(pluginName, UUID.randomUUID().toString(), getName());
    pluginUser.addObjectPermission(new WildcardPermission(permissions));
    this.add(pluginUser);
}

From source file:com.github.ibole.infrastructure.web.security.spring.shiro.realm.FormRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
    logger.debug("doGetAuthenticationInfo from DB.");
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    UserModel user = wsService.findWsUser(upToken.getUsername(), upToken.getPassword().toString());
    if (user != null) {
        SimpleAccount account = new SimpleAccount(user.getUserId(), null, getName());
        return account;
    }//from   w  w w .ja v  a 2  s.  c  om

    return null;
}

From source file:com.kalix.framework.webapp.shiro.DemoRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
    User user = userDao.findUser(upToken.getUsername());
    if (user == null) {
        throw new AuthenticationException();
    }//from  w w w.  j  a  va2  s.com
    return new SimpleAccount(user, user.getHashedPassword(), getName());
}

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 ww .j  av a2 s .c o  m
 * 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.parallax.server.blocklypropauth.security.SimpleAuthenticationRealm.java

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    try {//  w w  w . j a v a  2 s .  c o  m
        if (token instanceof IdAuthenticationToken) {
            Long idUser = (Long) token.getPrincipal();

            try {
                return new SimpleAccount(idUser, "", "SimpleAuthentication");
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    } catch (NullPointerException npe) {
        log.warn("NullPointer", npe);
    } catch (Throwable t) {
        log.warn("Throwable", t);
    }
    return null;
}

From source file:com.rainy.shiro.demo.MyRealm.java

License:Apache License

/**
 * Simulates a call to an underlying data store - in a 'real' application, this call would communicate with
 * an underlying data store via an EIS API (JDBC, JPA, Hibernate, etc).
 * <p/>//from   www  .j a  v a 2  s .com
 * Note that when implementing your own realm, there is no need to check against a password (or other credentials)
 * in this method. The {@link org.apache.shiro.realm.AuthenticatingRealm AuthenticatingRealm} superclass will do
 * that automatically via the use of a configured
 * {@link org.apache.shiro.authc.credential.CredentialsMatcher CredentialsMatcher} (see this example's corresponding
 * {@code shiro.ini} file to see a configured credentials matcher).
 * <p/>
 * All that is required is that the account information include directly the credentials found in the EIS.
 *
 * @param username the username for the account data to retrieve
 * @return the Account information corresponding to the specified username:
 */
protected SimpleAccount getAccount(String username) {
    //just create a dummy.  A real app would construct one based on EIS access.
    SimpleAccount account = new SimpleAccount(username, "sha256EncodedPasswordFromDatabase", getName());
    //simulate some roles and permissions:
    account.addRole("user");
    account.addRole("admin");
    //most applications would assign permissions to Roles instead of users directly because this is much more
    //flexible (it is easier to configure roles and then change role-to-user assignments than it is to maintain
    // permissions for each user).
    // But these next lines assign permissions directly to this trivial account object just for simulation's sake:
    account.addStringPermission("blogEntry:edit"); //this user is allowed to 'edit' _any_ blogEntry
    //fine-grained instance level permission:
    account.addStringPermission("printer:print:laserjet2000"); //allowed to 'print' to the 'printer' identified
    //by the id 'laserjet2000'

    return account;
}

From source file:com.whale.eos.service.org.ShiroDbRealm.java

License:Apache License

/**
 * ?,.//from  w  w w. jav  a  2  s  .co  m
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    if (useCaptcha) {
        CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken;
        String parm = token.getCaptcha();
        String c = (String) SecurityUtils.getSubject().getSession()
                .getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        if (parm == null || !parm.equalsIgnoreCase(c)) {
            throw new IncorrectCaptchaException(ResourceUtils.getString("msg.login.kaptcha.code.error"));
        }
    }
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
    // System.out.println("token.getUsername() : " + token.getUsername());
    EosEmp eosEmp = eosEmpService.findByEno(token.getUsername());
    // byte[] salt = Encodes.decodeHex(operator.getPwdSalt());
    // byte[] salt = Encodes.decodeHex(PropertyUtil.getString("salt"));
    if (eosEmp != null) {
        if (PropertyUtil.getBoolean("encrypt")) {
            return new SimpleAuthenticationInfo(
                    new ShiroEmp(String.valueOf(eosEmp.getId()), eosEmp.getEno(), eosEmp.getEname()),
                    eosEmp.getEpwd(), ByteSource.Util.bytes(Encodes.decodeHex(PropertyUtil.getString("salt"))),
                    getName());
        } else {
            return new SimpleAccount(
                    new ShiroEmp(String.valueOf(eosEmp.getId()), eosEmp.getEno(), eosEmp.getEname()),
                    eosEmp.getPwd(), getName());
        }

    } else {
        throw new UnknownAccountException();
    }
}

From source file:org.apache.zeppelin.realm.jwt.KnoxJwtRealm.java

License:Apache License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
    JWTAuthenticationToken upToken = (JWTAuthenticationToken) token;

    if (validateToken(upToken.getToken())) {
        try {/*from www  .jav a 2  s .co  m*/
            SimpleAccount account = new SimpleAccount(getName(upToken), upToken.getToken(), getName());
            account.addRole(mapGroupPrincipals(getName(upToken)));
            return account;
        } catch (ParseException e) {
            LOGGER.error("ParseException in doGetAuthenticationInfo", e);
        }
    }
    return null;
}

From source file:org.apache.zeppelin.realm.kerberos.KerberosRealm.java

License:Apache License

/**
 * This is called when Kerberos authentication is done and a {@link KerberosToken} has
 * been acquired./*from w  w w  .  j  a  v a  2 s.c o  m*/
 * This function returns a Shiro {@link SimpleAccount} based on the {@link KerberosToken}
 * provided. Null otherwise.
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
        org.apache.shiro.authc.AuthenticationToken authenticationToken)
        throws org.apache.shiro.authc.AuthenticationException {
    if (null != authenticationToken) {
        KerberosToken kerberosToken = (KerberosToken) authenticationToken;
        SimpleAccount account = new SimpleAccount(kerberosToken.getPrincipal(), kerberosToken.getCredentials(),
                kerberosToken.getClass().getName());
        account.addRole(mapGroupPrincipals((String) kerberosToken.getPrincipal()));
        return account;
    }
    return null;
}