Searching users in Keycloak from Java code - java

I am using Spring Boot, Keycloak 10, java 8 and keycloak-admin-client jar. I am able to get user, his groups and roles.
When it comes to search I see different search method options for example I could :
List<UserRepresentation> search = getKeycloakInstance().realm("my-realm").users()
.search("username");
https://www.keycloak.org/docs-api/10.0/javadocs/org/keycloak/admin/client/resource/UsersResource.html
But what i need to do i to write couple of methods:
search by roles (so search users who has some roles)
search by groups and group attributes
search by text (firstname, lastname, email) in 'contains' manner: mytext
search by roles and text
search by list of ids (uuids of users)
I dont' see such possibilities in keycloak-admin-client, or it is possible of what else should I use instead of keycloak-admin-client ?

Unfortunately, keycloak-admin-client doesn't provide lots of search options.
How to find users by role:
RoleResource roleResource = getKeycloakInstance().realm("realm_name")
.roles().get("role_name");
roleResource.getRoleUserMembers();
How to find all users in the group:
getKeycloakInstance().realm("realm_name").groups().group("your_group").members();
How to find users by username, firstName, lastName, email:
getKeycloakInstance().realm("my-realm").users()
.search("username", "lastName", "email");
If it's okay for you, try to use Keycloak Admin REST API to get more search opportunities.

Related

VMM how to find or fetch VMM entity attribute mapping / attribute names

Starting point:
I have a WebSphere with federated security (there is an Active Directory behind it).
I am trying to fetch a VMM user uid by his/her email address, but I a don't know how it's VMM (schema) attributes are mapped to the AD (schema) attributes of the underlying Active Directory entity (person, organizationalPerson objectClass, mail attribute.
(By describing it in a different way: If one have a look at the WAS console, in the "Users and Groups" -> "Manage Users" there is a table where there is an E-Mail column, so it is somehow mapped.
But, by clicking on the ( "Global Security" -> "(federated repositories) configure button" -> (there is a table, you can select the)) LDAP1 row, and checking the table in "Federated repositories property names to LDAP attributes mapping", I don't find that the 'E-Mail' column how has been mapped to the AD attribute. Maybe there is an implicit mapping?)
So, the starting question is this:
How to find this on the WAS console? Or, maybe via wsadmin (scripts)?
So, because of this, I tried to move forward and now I would try to find it using the VMM API, but I don't find in the official documentation the answer to the second question:
Is it possible to fetch somehow the assigned / available attributes of an WebSphere VMM entity (Virtual member manager)?
There is a lot of examples about how to fetch the attributes when you know their name, but there is nothing about this...
Yes, I know that is is a bit XY problem, but please guide me a bit.
Many thanks in advance.
To provide some code sample too, I am trying to fetch the user's uid by using the following code:
public String testFetch(String email) throws Exception
{
String returnAttr = "uid";
// here in the search expression what should I wrire instead of the 'mail'?
String vmmSearchExpr = String.format("#xsi:type='PersonAccount' and mail='%s'", email);
DataObject root = SDOHelper.createRootDataObject();
DataObject searchCtrl = SDOHelper.createControlDataObject(root, null, SchemaConstants.DO_SEARCH_CONTROL);
searchCtrl.setString(SchemaConstants.PROP_SEARCH_EXPRESSION, vmmSearchExpr);
#SuppressWarnings("unchecked")
List<String> props = searchCtrl.getList(SchemaConstants.PROP_PROPERTIES);
props.add(returnAttr);
Service service = new LocalServiceProvider(null);
DataObject searchRoot = service.search(root);
String result = "";
List<?> entities = searchRoot.getList(SchemaConstants.DO_ENTITIES);
if (entities.size() > 1) throw new RuntimeException("multiple users for an identity:" + vmmSearchExpr);
if (entities.size() > 0)
{
DataObject objdo = (DataObject) entities.get(0);
result = objdo.getString(returnAttr);
}else{
log("Got empty list There is no result.");
}
return result;
}
A possible solution is to add a new federal repository supported property (Name: mail, Property name: mail, Entity types: PersonAccount):
After a WAS restart I was able to use the search expression
#xsi:type='PersonAccount' and mail='<email address>'
and the code above to fetch the corresponding uid to the given email address.
It seems there is some info in the c:\IBM\WebSphere\AppServer\etc\wim\setup\wimdbproperties.xml, as if the "ibm-primaryEmail" would be the property that contains the email address, albeit I was not able to find my uid when I specified this instead of the "mail" attribute name.

How to search users inside group in Keycloak?

Using Keycloak 11.0.3.
I trying to search users inside group using Keycloak API:
List<UserRepresentation> users = realmResource.users().search(username, firstname, lastname, email,
0, 100);
But when I try to get groups of found users I get null even if user have group:
List<String> groups = users.get(0).getGroups(); //It's null
So how to search users inside group?
To get the groups that a user belongs to try with the following:
realm.users().get(userId).groups();
Use the userID instead.
To get the users of a given group do the following:
realm.groups().group(groupId).members();

Username contain Specific word in Twitter API Using Java

How can I search for a word in twitter's users?
for example how can I find all users who has in their names or usernames the word "James"?
If I use twitter.showUser(username) it will return a single user IF IT EXISTS!
I want all the users who may contain username in their usernames or names. I'm using Twitter4J in my application.
Probably the way to go:
Get a list of all available users (http://twitter4j.org/oldjavadocs/4.0.0/twitter4j/api/UsersResources.html#searchUsers-java.lang.String-int-)
Iterate data.stream().anyMatch(x -> x.name.contains('James')).collect(toList)

LDAP: Get list of users in a specific group

I'm trying to get all users of a specific user group. I'm doing this in java, I can connect to ldap and get results from different queries. However I've searched to find solution but as far as I can tell the LDAP of my workplace is structured differently than what seems normal.
dn of users:
ou=Users,O=MYCOMPANY.COM
dn of the user group:
cn=Admin,ou=Profiles,ou=MYAPP,ou=Applirights,O=MYCOMPANY.COM
For the user group, cn is the privilege level / group name (Admin) and the name of the application is in an organisational unit. With this structure, how would I query for all users in this specific group?
I tried:
NamingEnumeration<?> namingEnum = ctx.search("ou=Users,O=MYCOMPANY.COM", "(cn=Admin,ou=Profiles,ou=MYAPP,ou=Applirights,O=MYCOMPANY.COM)", searchControls);
However what attributes would need to be in search controls? I use uid which is the users login name.
I also tried whats outlined here:
(&(objectCategory=user)(memberOf=cn=Admin,ou=MYAPP,ou=Applirights,O=MYCOMPANY.COM))
Nothing works and with that, I mean I get 0 results but no error. How can I achieve this with the given organisation of ldap?
Groups have something called memberOf:
So try this:
search -s sub -b "DC=whatever,DC=mydomain,DC=com" "(&(objectCategory=user)(memberOf=CN=GROUP,DC=whatever,DC=mydomain,DC=com))"
you fill in whatever mydomain and GROUP above ^
What attributes would need to be in search controls?
The attributes listed in searchControls are the ones you want returned. The one containing the group members. Depending on what objectClass the group object is, it might be:
uniqueMember for groupOfUniqueNames
roleOccupant for organizationalRole
and so forth.

Getting all users with a Role in Liferay

I'm new to Liferay development in general, so feel free to point out if I'm going about stuff totally the wrong way.
I'm trying to get a DynamicQuery object of all users within a certain group (I'll use this object to further filter another query I'll do against the message board). The User interface seems to have a roleIds property that I might be able to use, since I already know the roleId I'm interested in. But I can't find the proper way to query if roleIds contains a certain value.
Any ideas on what I want to do?
PS: I would have the exact SQL query I could ask directly, but I'd rather use Liferay's own connection pool, without needing to do some weird ext project thingy.
You don't need a DynamicQuery. These are the methods you are looking for in the classes that Dirk points out:
long[] UserServiceUtil.getRoleUserIds(long roleId)
or
long[] UserLocalServiceUtil.getRoleUserIds(long roleId)
List<User> UserLocalServiceUtil.getRoleUsers(long roleId)
Remember that the methods in the classes XXXLocalServiceUtil are not checking the permissions of the current user.
EDIT: If you are looking for all users with a given role within a given community:
long companyId= _X_; //Perhaps CompanyThreadLocal.getCompanyId() if you don't have it anywhere else?
Role role=RoleLocalServiceUtil.getRole(companyId, "Example Role");
Group group=GroupLocalServiceUtil.getGroup(companyId, "Example Community");
List<UserGroupRole> userGroupRoles = UserGroupRoleLocalServiceUtil.
getUserGroupRolesByGroupAndRole(groupId, role.getRoleId());
for(UserGroupRole userGroupRole:userGroupRoles){
User oneUser=userGroupRole.getUser();
}
The easiest way to access liferays own objects is by using the XXXServiceUtil classes (e.g. RoleServiceUtil.getUserRoles(userId)). Thus you rarely have to deal with any SQL directly. Either the RoleServiceUtil or UserServiceUtil might have what you need.
The roles of an Organizations are stored in the table UserGroupRole, so if you want to get the owner of an Organization you must use the following code:
boolean isOrgOwner =
UserGroupRoleLocalServiceUtil.hasUserGroupRole(
usr.getUserId(),
this.currentOrganization.getGroupId(),
RoleConstants.ORGANIZATION_OWNER);
If you want to retrieve all the Organization Owners of an organization:
List<User> administrators = new LinkedList<>();
List<UserGroupRole> allOrganizationAdministrators =
UserGroupRoleLocalServiceUtil.getUserGroupRolesByGroupAndRole(
this.currentOrganization.getGroupId(), roleId);
for (UserGroupRole userGroupRoleTemp : allOrganizationAdministrators) {
administrators.add(userGroupRoleTemp.getUser());
}
Cheers!

Categories

Resources