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> roleNames,
        Set<Permission> permissions) 

Source Link

Document

Constructs a SimpleAccount instance from the given principals and credentials, with the the assigned roles and permissions.

Usage

From source file:co.edu.uniandes.csw.miso4204.security.SecurityRealm.java

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    SimpleAccount account = null;// w ww.jav  a 2  s.c om

    JwtToken authToken = (JwtToken) token;
    if (authToken.getToken() != null) {
        //Descifrar token y establecer info de usuario
        UserDTO user = decodeUser(authToken.getToken());
        if (validarToken(user)) {
            account = new SimpleAccount(user.getUsername(), user.getPassword(),
                    ByteSource.Util.bytes(authToken.getToken()), REALM);
        }
    }
    return account;
}

From source file:demo.learn.shiro.pojo.UserTest.java

License:Apache License

/**
 * Tests de-salting./*from   www.ja va  2 s  .  c om*/
 */
public void testDesalting() {
    try {
        String username = "user1";
        String plainTextPassword = "hello";
        RandomNumberGenerator rng = new SecureRandomNumberGenerator();
        ByteSource salt = rng.nextBytes();

        String hashedPasswordBase64 = new Sha256Hash(plainTextPassword, salt, 1024).toBase64();

        User user = new User(username, hashedPasswordBase64);
        user.setPasswordSalt(salt);

        UsernamePasswordToken token = new UsernamePasswordToken(username, plainTextPassword);
        //         SimpleByteSource desalt = new SimpleByteSource(salt);
        byte[] bytes = salt.getBytes();
        String base64 = Base64.encodeToString(bytes);
        SimpleByteSource desalt1 = new SimpleByteSource(Base64.decode(base64));

        SimpleAccount info = new SimpleAccount(user, hashedPasswordBase64, desalt1, "learn.shiro");

        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher("SHA-256");
        matcher.setHashIterations(1024);
        matcher.setStoredCredentialsHexEncoded(false);

        boolean result = matcher.doCredentialsMatch(token, info);
        Assert.assertEquals(true, result);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.assertEquals(ex.getMessage(), false, true);
    }
}

From source file:demo.learn.shiro.pojo.UserTest.java

License:Apache License

/**
 * Tests two salting./*  ww w  . j ava  2 s . com*/
 */
public void testTwoSalting() {
    try {
        String username1 = "user1";
        String username2 = "user2";
        String plainTextPassword1 = "hello";
        String plainTextPassword2 = "hello";

        RandomNumberGenerator rng = new SecureRandomNumberGenerator();
        ByteSource salt1 = rng.nextBytes();
        ByteSource salt2 = rng.nextBytes();

        String hashedPasswordBase641 = new Sha256Hash(plainTextPassword1, salt1, 1024).toBase64();
        String hashedPasswordBase642 = new Sha256Hash(plainTextPassword2, salt2, 1024).toBase64();

        User user1 = new User(username1, hashedPasswordBase641);
        User user2 = new User(username2, hashedPasswordBase642);
        user1.setPasswordSalt(salt1);
        user2.setPasswordSalt(salt2);

        UsernamePasswordToken token1 = new UsernamePasswordToken(username1, plainTextPassword1);
        UsernamePasswordToken token2 = new UsernamePasswordToken(username2, plainTextPassword2);

        SimpleAccount info1 = new SimpleAccount(user1, hashedPasswordBase641, salt1, "learn.shiro");
        SimpleAccount info2 = new SimpleAccount(user2, hashedPasswordBase642, salt2, "learn.shiro");

        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher("SHA-256");
        matcher.setHashIterations(1024);
        matcher.setStoredCredentialsHexEncoded(false);

        boolean result = matcher.doCredentialsMatch(token1, info1);
        Assert.assertEquals(true, result);

        result = matcher.doCredentialsMatch(token2, info2);
        Assert.assertEquals(true, result);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.assertEquals(ex.getMessage(), false, true);
    }
}

From source file:org.commonjava.auth.shiro.couch.CouchRealm.java

License:Apache License

@Override
protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals) {
    final Object principal = principals.getPrimaryPrincipal();
    User user;/*from  www  . j  a  v  a2  s  . co  m*/
    try {
        user = dataManager.getUser(principal.toString());
    } catch (final UserDataException e) {
        logger.error("Failed to retrieve user: %s. Reason: %s", e, principal, e.getMessage());

        throw new AuthenticationException("Cannot retrieve user. System configuration is invalid.");
    }

    if (user == null) {
        throw new AuthenticationException("Authentication failed: " + principal);
    }

    final Set<String> roleNames = new HashSet<String>();
    final Set<Permission> perms = new HashSet<Permission>();
    if (user.getRoles() != null) {
        Set<Role> roles;
        try {
            roles = dataManager.getRoles(user);
        } catch (final UserDataException e) {
            logger.error("Failed to retrieve roles for user: %s. Reason: %s", e, principal, e.getMessage());

            throw new AuthenticationException("Cannot retrieve user roles. System configuration is invalid.");
        }

        for (final Role role : roles) {
            roleNames.add(role.getName());

            Set<org.commonjava.couch.rbac.Permission> permissions;
            try {
                permissions = dataManager.getPermissions(role);
            } catch (final UserDataException e) {
                logger.error("Failed to retrieve permissions for role: %s. Reason: %s", e, role.getName(),
                        e.getMessage());

                throw new AuthenticationException(
                        "Cannot retrieve role permissions. System configuration is invalid.");
            }

            if (permissions != null) {
                for (final org.commonjava.couch.rbac.Permission perm : permissions) {
                    perms.add(new ShiroPermission(perm));
                }
            }
        }
    }

    return new SimpleAccount(principals, user.getPasswordDigest(), roleNames, perms);
}

From source file:org.commonjava.badgr.shiro.BadgrRealm.java

License:Apache License

@Override
protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals) {
    final Object principal = principals.getPrimaryPrincipal();
    User user;/*w ww .j av  a  2 s. c om*/
    try {
        user = dataManager.getUser(principal.toString());
    } catch (final BadgrDataException e) {
        logger.error("Failed to retrieve user: %s. Reason: %s", e, principal, e.getMessage());

        throw new AuthenticationException("Cannot retrieve user. System configuration is invalid.");
    }

    if (user == null) {
        throw new AuthenticationException("Authentication failed: " + principal);
    }

    final Set<String> roleNames = new HashSet<String>();
    final Set<Permission> perms = new HashSet<Permission>();
    if (user.getRoles() != null) {
        Set<Role> roles;
        try {
            roles = dataManager.getRoles(user);
        } catch (final BadgrDataException e) {
            logger.error("Failed to retrieve roles for user: %s. Reason: %s", e, principal, e.getMessage());

            throw new AuthenticationException("Cannot retrieve user roles. System configuration is invalid.");
        }

        for (final Role role : roles) {
            roleNames.add(role.getName());

            Set<org.commonjava.badgr.model.Permission> permissions;
            try {
                permissions = dataManager.getPermissions(role);
            } catch (final BadgrDataException e) {
                logger.error("Failed to retrieve permissions for role: %s. Reason: %s", e, role.getName(),
                        e.getMessage());

                throw new AuthenticationException(
                        "Cannot retrieve role permissions. System configuration is invalid.");
            }

            if (permissions != null) {
                for (final org.commonjava.badgr.model.Permission perm : permissions) {
                    perms.add(new ShiroPermission(perm));
                }
            }
        }
    }

    return new SimpleAccount(principals, user.getPasswordDigest(), roleNames, perms);
}

From source file:org.graylog2.security.realm.PasswordAuthenticator.java

License:Open Source License

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken)
        throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authToken;
    LOG.debug("Retrieving authc info for user {}", token.getUsername());

    final User user = userService.load(token.getUsername());
    if (user == null || user.isLocalAdmin()) {
        // skip the local admin user here, it's ugly, but for auth that user is treated specially.
        return null;
    }/*from   ww  w .jav  a 2s.c o  m*/
    if (user.isExternalUser()) {
        // we don't store passwords for LDAP users, so we can't handle them here.
        LOG.trace("Skipping mongodb-based password check for LDAP user {}", token.getUsername());
        return null;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Found user {} to be authenticated with password.", user.getName());
    }
    return new SimpleAccount(token.getPrincipal(), user.getHashedPassword(),
            ByteSource.Util.bytes(configuration.getPasswordSecret()), "graylog2MongoDbRealm");
}

From source file:org.i3xx.step.zero.security.impl.shiro.NaMyRealm.java

License:Apache License

protected SimpleAccount getAccount(String username, Object credentials) {

    //TODO: Remove the System.out
    System.out.println("get account user: " + username);
    //Account account = new SimpleAccount(username, "sha256EncodedPasswordFromDatabase", getName());

    if (username == null)
        throw new AccountException("Null usernames are not allowed by this realm.");
    //Account account=_store.getAccounts().get(username);
    //if (account == null) throw new UnknownAccountException("No account found for user [" + username + "]");
    String hash = _hash/*account.getPasswordHash()*/;
    ByteSource salt = new SimpleByteSource(_salt/*account.getSalt()*/);

    SimpleAccount account = new SimpleAccount(username, hash, salt, getName());

    //SimpleAccount account = new SimpleAccount(username, "sha256EncodedPasswordFromDatabase", getName());
    account.addRole("user");
    account.addRole("admin");
    account.addStringPermission("blogEntry:edit");
    account.addStringPermission("printer:print:laserjet");

    //The password or private key
    account.setCredentials(credentials);

    return account;
}

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");
    }//from  www.  ja  v  a 2 s .c o  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;
}