@Override protected void add(SimpleAccount account) { String username = (String)account.getPrincipals().getPrimaryPrincipal(); // Let's add some additional principals for testing SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(); principalCollection.addAll(account.getPrincipals()); principalCollection.add(counter.getAndIncrement(), "integerRealm"); TestObjPrincipal objPrinc = new TestObjPrincipal(username.toUpperCase()+" "+username.toUpperCase()); principalCollection.add(objPrinc, "objRealm"); account.setPrincipals(principalCollection); super.add(account); //To change body of generated methods, choose Tools | Templates. }
protected void beforeAssertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { SimpleAccount account = (SimpleAccount) info; if (account != null) { // only set credentials salt on the first time!!! ByteSource credentialsSalt = (ByteSource) account.getCredentialsSalt(); if (credentialsSalt == null) { Object credentials = account.getCredentials(); credentialsSalt = ByteSource.Util.bytes(credentials); account.setCredentialsSalt(credentialsSalt); account.setCredentials(null); } Object oldCredentials = account.getCredentials(); Object stringToSign = hmacBuilder.buildStringToSign((HmacToken) token); account.setCredentials(stringToSign); if (log.isDebugEnabled()) { log.debug("oldCredentials: {}", oldCredentials); log.debug("curCredentials: {}", account.getCredentials()); log.debug("credentialsSalt: {}", account.getCredentialsSalt().toHex()); } } }
@Override protected Realm createRealm(Ini ini) { // Set the resolvers first, because IniRealm is initialized before the resolvers // are applied by the ModularRealmAuthorizer IniRealm realm = new IniRealm() { @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { SimpleAccount account = (SimpleAccount) super.doGetAuthorizationInfo(principals); // implicitly, give the role agate-user to all users from ini if(account != null) account.addRole(Roles.AGATE_USER.toString()); return account; } }; realm.setName(INI_REALM); // realm.setRolePermissionResolver(rolePermissionResolver); realm.setPermissionResolver(permissionResolver); realm.setResourcePath(getShiroIniPath()); realm.setCredentialsMatcher(new PasswordMatcher()); realm.setIni(ini); return realm; }
@Override public SimpleAccount getAccountFromAccessToken(String accessToken) { User user = null; try { user = usersDao.findByOAuthAccessToken(accessToken); } catch (Exception e) { LOGGER.error(String.format("Can't find user from OAuth2 access token '%s'", accessToken), e); } if (user == null) return null; Set<String> roles = user.getRoles().stream() .map(Enum::name) .collect(toSet()); Set<Permission> permissions = user.getRoles().stream() .flatMap(role -> role.getPermissions().stream()) .map(WildcardPermission::new) .collect(toSet()); return new SimpleAccount(user.getUsername(), accessToken, OAuth2Realm.class.getSimpleName(), roles, permissions); }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; SimpleAccount account = getAccountFromUsername(upToken.getUsername()); if (account != null) { if (account.isLocked()) { throw new LockedAccountException("Account [" + account + "] is locked."); } if (account.isCredentialsExpired()) { String msg = "The credentials for account [" + account + "] are expired"; throw new ExpiredCredentialsException(msg); } } return account; }
private SimpleAccount getAccountFromUsername(String username) { User user = null; try { user = usersDao.findByUsername(username); } catch (Exception e) { LOGGER.error("Can't find user '{}'", e); } if (user == null) return null; Set<String> roles = user.getRoles().stream() .map(Enum::name) .collect(toSet()); Set<Permission> permissions = user.getRoles().stream() .flatMap(role -> role.getPermissions().stream()) .map(WildcardPermission::new) .collect(toSet()); return new SimpleAccount(user.getUsername(), user.getPassword(), user.getName(), roles, permissions); }
/** * Changes the password of a user. * * @param name * the name of the user to be modified * @param password * the new password of the user * * @throws ForwardedRuntimeException * if a user with {@code name} does not exist, the exception * wraps a {@code AuthManagementException} */ public void modifyPassword(final String name, final String password) throws ForwardedRuntimeException { if (isClosed()) { throw new ForwardedRuntimeException(AuthManagementException.class, 1003); } final SimpleAccount account = this.users.get(name); if (account == null) { throw new ForwardedRuntimeException(AuthManagementException.class, 1001, name); } else { if (LOG.isTraceEnabled()) { LOG.trace("Modifying password of user '" + name + "'."); } // set the new credentials final SimpleAccount clone = clone(account); clone.setCredentials(password); this.users.put(name, clone); db.commit(); } }
/** * Clones a {@code SimpleAccount} instance. The MapDb documentation suggests * that a persisted instance should be immutable. * * @param account * the account to be cloned * * @return the cloned instance */ protected SimpleAccount clone(final SimpleAccount account) { if (account == null) { return null; } final Set<String> roles; if (account.getRoles() == null) { roles = null; } else { roles = new LinkedHashSet<String>(); roles.addAll(account.getRoles()); } final Set<Permission> permissions; if (account.getObjectPermissions() == null) { permissions = null; } else { permissions = new LinkedHashSet<Permission>(); permissions.addAll(account.getObjectPermissions()); } return new SimpleAccount(account.getPrincipals(), account.getCredentials(), roles, permissions); }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException { OAuth2Token token = (OAuth2Token) authToken; SimpleAccount account = authorizationServer.getAccountFromAccessToken(token.getToken()); if (account != null) { if (account.isLocked()) { throw new LockedAccountException("Account [" + account + "] is locked."); } if (account.isCredentialsExpired()) { String msg = "The credentials for account [" + account + "] are expired"; throw new ExpiredCredentialsException(msg); } } return account; }
@Override public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { if (supports(token)) { return new SimpleAccount(token.getPrincipal(), token.getCredentials(), getName()); } return null; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) { JWTAuthenticationToken upToken = (JWTAuthenticationToken) token; if (validateToken(upToken.getToken())) { try { 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; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) { UsernamePasswordToken upToken = (UsernamePasswordToken) token; UserDefault user = userRepository.findByUserId(upToken.getUsername()); if (user != null) { SimpleAccount account = new SimpleAccount(user, user.getCredentials(), getName()); account.addRole(user.getRoles()); return account; } return null; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) { JWTAuthenticationToken upToken = (JWTAuthenticationToken) token; UserDefault user = userRepository.findById(upToken.getUserId()); if (user != null && userRepository.validateToken(upToken.getToken())) { SimpleAccount account = new SimpleAccount(user, upToken.getToken(), getName()); account.addRole(user.getRoles()); return account; } return null; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) { UsernamePasswordToken upToken = (UsernamePasswordToken) token; User user = userDao.findUser(upToken.getUsername()); if (user == null) { throw new AuthenticationException(); } return new SimpleAccount(user, user.getHashedPassword(), getName()); }
/** * Assigns the specified {@code role} to the specified {@code username}. * * @param username * the name of the user to assign the role to * @param role * the role to be assigned * * @throws AuthManagementException * if the realm is closed or if the user does not exist */ public void assignRoleToUser(final String username, final String role) throws AuthManagementException { if (isClosed()) { throw new ForwardedRuntimeException(AuthManagementException.class, 1003); } else if (!validateRole(role)) { throw new ForwardedRuntimeException(AuthManagementException.class, 1006, role); } final SimpleAccount account = this.users.get(username); if (account == null) { throw new ForwardedRuntimeException(AuthManagementException.class, 1004, role, username); } else { if (LOG.isTraceEnabled()) { LOG.trace("Assigning role '" + role + "' to user '" + username + "'."); } final SimpleAccount clone = clone(account); clone.addRole(role); this.users.put(username, clone); db.commit(); } }
/** * Removes the specified {@code role} from the specified {@code username}. * * @param username * the name of the user to remove the role from * @param role * the role to be removed * * @throws AuthManagementException * if the realm is closed or if the user does not exist */ public void removeRoleFromUser(final String username, final String role) throws AuthManagementException { if (isClosed()) { throw new ForwardedRuntimeException(AuthManagementException.class, 1003); } final SimpleAccount account = this.users.get(username); if (account == null) { throw new ForwardedRuntimeException(AuthManagementException.class, 1005, role, username); } else { if (LOG.isTraceEnabled()) { LOG.trace("Removing role '" + role + "' from user '" + username + "'."); } final SimpleAccount clone = clone(account); final Collection<String> roles = clone.getRoles(); if (roles != null && roles.size() > 0) { // we need a set so get one final Set<String> setOfRoles = cast(roles); setOfRoles.remove(role); // set null if there aren't any if (setOfRoles.size() == 0) { clone.setRoles(null); } else { clone.setRoles(setOfRoles); } this.users.put(username, clone); db.commit(); } } }
/** * Grants the specified {@code permissions} to the specified * {@code username}. * * @param username * the name of the user to grant the permissions to * @param permissions * the permissions to be granted (cannot be {@code null} or * empty) * * @throws AuthManagementException * if the permissions are empty, if the {@code username} does * not exist or if the realm is closed */ public void grantPermissionsToUser(final String username, final String[] permissions) throws AuthManagementException { if (isClosed()) { throw new ForwardedRuntimeException(AuthManagementException.class, 1003); } else if (permissions == null || permissions.length == 0) { throw new ForwardedRuntimeException(AuthManagementException.class, 1008, username); } final SimpleAccount account = this.users.get(username); if (account == null) { throw new ForwardedRuntimeException(AuthManagementException.class, 1009, Arrays.asList(permissions), username); } else { final List<String> perms = Arrays.asList(permissions); if (LOG.isTraceEnabled()) { LOG.trace("Granting '" + perms + "' to user '" + username + "'."); } final SimpleAccount clone = clone(account); clone.addObjectPermissions(PermissionUtils.resolvePermissions( perms, getPermissionResolver())); this.users.put(username, clone); db.commit(); } }
@Override protected AuthenticationInfo doGetAuthenticationInfo( final AuthenticationToken token) throws AuthenticationException { if (isClosed()) { throw new ForwardedRuntimeException(AuthManagementException.class, 1003); } final UsernamePasswordToken upToken = (UsernamePasswordToken) token; final SimpleAccount account = this.users.get(upToken.getUsername()); if (account != null) { if (account.isLocked()) { throw new LockedAccountException("Account [" + account + "] is locked."); } if (account.isCredentialsExpired()) { throw new ExpiredCredentialsException( "The credentials for account [" + account + "] are expired"); } } return account; }
/** * Gets the roles assigned to the specified {@code username}. * * @param username * the name of the user to retrieve the roles for * * @return the roles of the user */ public Set<String> getUserRoles(final String username) { final SimpleAccount account = this.users.get(username); final Set<String> roles = new LinkedHashSet<String>(); if (account != null) { final Collection<String> accountRoles = account.getRoles(); if (accountRoles != null) { roles.addAll(accountRoles); } } return roles; }
/** * This test verifies that the AbstractHash and Salt are functioning * correctly. */ @Test public void whenPasswordIsGeneratedTheCredentialsShouldMatch() { final CredentialsMatcher matcher = new SecurityModule(null).matcher(); final String salt = "abc"; final String plainPassword = "password"; final String hashedPassword = new UserFactory().hashPassword(plainPassword, salt); final AuthenticationInfo info = new SimpleAccount("admin", hashedPassword, SaltTool.getFullSalt(salt), "testrealm"); final AuthenticationToken token = new UsernamePasswordToken("admin", plainPassword); assertThat(matcher.doCredentialsMatch(token, info), is(true)); }
@Override protected void add(SimpleAccount account) { String username = (String) account.getPrincipals().getPrimaryPrincipal(); // Let's add some additional principals for testing SimplePrincipalCollection principalCollection = new SimplePrincipalCollection(); principalCollection.addAll(account.getPrincipals()); principalCollection.add(counter.getAndIncrement(), "integerRealm"); TestObjPrincipal objPrinc = new TestObjPrincipal(username.toUpperCase() + " " + username.toUpperCase()); principalCollection.add(objPrinc, "objRealm"); account.setPrincipals(principalCollection); super.add(account); }
/** * Returns all the users currently defined for this UserRealm * * @return the map of users */ public Map<String, User> getUsers() { HashMap<String, User> accounts = new HashMap<>(); for (Map.Entry<String, SimpleAccount> user : users.entrySet()) { accounts.put(user.getKey(), (User) user.getValue()); } return accounts; }
/** * Adds a user to the realm using the specified {@code name} and * {@code password}. It is possible to assign {@code roles} to the user, as * well as {@code permissions}. * * @param name * the name of the user * @param password * the password * @param roles * the roles, can be {@code null} * @param permissions * the permissions, can be {@code null} * * @throws ForwardedRuntimeException * if an other already exists with the same {@code name}, the * exception wraps a {@code AuthManagementException} */ public void addUser(final String name, final String password, final String[] roles, final String[] permissions) throws ForwardedRuntimeException { if (isClosed()) { throw new ForwardedRuntimeException(AuthManagementException.class, 1003); } else if (!validateUser(name)) { throw new ForwardedRuntimeException(AuthManagementException.class, 1007, name); } else if (this.users.containsKey(name)) { throw new ForwardedRuntimeException(AuthManagementException.class, 1000, name); } else { if (LOG.isTraceEnabled()) { LOG.trace("Adding user '" + name + "' with roles '" + (roles == null ? null : Arrays.asList(roles)) + "' and permissions '" + (permissions == null ? null : Arrays .asList(permissions)) + "'."); } // create the account final SimpleAccount account = new SimpleAccount(name, password, getName()); // set the roles if (roles != null && roles.length > 0) { account.addRole(Arrays.asList(roles)); } // set the permissions for the account if (permissions != null && permissions.length > 0) { final Set<Permission> perms = PermissionUtils .resolvePermissions(Arrays.asList(permissions), getPermissionResolver()); account.setObjectPermissions(perms); } // add the user to the map this.users.put(name, account); db.commit(); } }
public void addPlugin(String pluginName, String permissions) { SimpleAccount pluginUser = new SimpleAccount(pluginName, UUID.randomUUID().toString(), getName()); pluginUser.addObjectPermission(new WildcardPermission(permissions)); this.add(pluginUser); }
SimpleAccount getAccountFromAccessToken(String token);