How to search users inside group in Keycloak? - java

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();

Related

Searching users in Keycloak from Java code

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.

Find user's member of groups in Microsoft AD inside Domain Users security group

I need to find the member of groups of a given user in Microsoft active directory using java inside the Domain Users group. My AD structure is below.
reg1.subdomain.domain.com
-Users (Type - Container)
- Domain Users (Type - Security Group Global)
I wrote the below code. But I was unable to query the users inside Domain Users group.
public static String ldapUri = "ldap://ldapuri.com:389";
public static String usersContainer = "CN=users,DC=reg1,DC=subdomain,DC=domain,DC=com";
public ArrayList<String> getUserGroups(String username, String password){
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUri);
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
DirContext ctx = new InitialDirContext(env);
SearchControls ctls = new SearchControls();
String[] attrIDs = { "memberOf" };
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
NamingEnumeration answer = ctx.search(usersContainer, "(&(objectCategory=group)(cn=Domain Users)(sAMAccountName=username))", ctls);
while (answer.hasMore()) {
SearchResult rslt = (SearchResult) answer.next();
Attributes attrs = rslt.getAttributes();
try{
String groups = attrs.get("memberOf").toString();
String [] groupname = groups.split(":");
System.out.println(groupname[1]);
}catch (Exception e){
System.out.println("no members");
}
}
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
return list;
}
Can someone please point out what's wrong with the filter query I have added?
The Domain Users group is a A Global Group Security Group that, by default, includes all user accounts in a domain. When you create a user account in a domain, it is added to this group by default.
Most methods do not reveal membership in the "primary" group. For most users, the "primary" group would be "Domain Users". Specifically, the memberOf attribute of user objects, and the member attribute of group objects, never reveals "primary" group membership. In most domains, the member attribute of the "Domain Users" group is empty, and it is safe to assume that all users belong to this group.
Domain Users LDAP Query Examples for all users that have "Domain Users" designated as their "primary", search for all users whose primaryGroupID attribute is 513 (by default). The primaryGroupID attribute of the group "Domain Users" is the same integer, 513. The LDAP syntax LDAP SearchFilter could be:
(primaryGroupID=513)
This ASSUMES you have not changed the Defaults and not created any users which have a primaryGroupID that is NOT 513.
For users within the "Domain Users" group JUST use (primaryGroupID=513) and the baseDN where the users are (CN=Users by default) which will return the DN of the users.
Then to get ALL the groups that these Users are a membeOf you will need to loop through the results using the DN in another query similer to:
(member:1.2.840.113556.1.4.1941:=(CN=UserName,CN=Users,DC=YOURDOMAIN,DC=NET))
As shown All Groups a User is a member of including Nested Groups
Oh and normally, the users within CN=Users will also USUALLY be the same as the members within the pseudo-group "Domain Users".
Assuming the base usersContainer is set correctly, you just need to change the filter as follows :
Searching for a user entry, you need to fix objectCategory to filter users - not groups. You may also use an equivalent like objectClass=inetOrgPerson.
Unless the user entry you are searching for actually really has the attribute cn=Domain Users (which is rather unlikely as a user's common name), you don't need this part.
So the following should be sufficient :
ctx.search(usersContainer, "(&(objectCategory=person)(sAMAccountName=username))", ctls);
To match specific user group membership(s) you would just add filter(s) on the memberOf attribute (returns matching user entry only if user is memberOf the given group), eg. :
(&(objectCategory=person)(sAMAccountName=username)(memberOf=<groupDN>))
Note as #jwilleke stated that if you target special groups that don't maintain membership attributes (group:member/user:memberOf), you need to use primaryGroupID instead of memberOf.
That said, since sAMAccountName is unique among all security principal objects within the domain, instead of adding a filter you may just need to use UserPrincipalName :
(&(objectCategory=person)(UserPrincipalName=username#domain.com))
the given code snippet above is correct except the searching method that I have specified. I was not able to search the users inside Domain Users group from Users container because I have not mentioned to search in sub directories. By adding search scope to,
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
it was able to successfully retrieve the users

Contacts group GROUP_VISIBLE and GROUP_IS_READ_ONLY ignored?

Can someone explain me why this parameters GROUP_IS_READ_ONLY (set to 0) and GROUP_VISIBLE (set to false) are ignored when my group is created?
I can still see group and contacts in it and also I can delete/modify my group and contacts in it.
EDIT
This is how I create a group:
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newInsert(Groups.CONTENT_URI)
.withValue(Groups.TITLE, groupName)
.withValue(Groups.ACCOUNT_NAME, accountName)
.withValue(Groups.ACCOUNT_TYPE, AccountGeneral.ACCOUNT_TYPE)
.withValue(Groups.GROUP_VISIBLE, false)
.withValue(Groups.GROUP_IS_READ_ONLY, 1)
.build());
mContentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
And this is what official developer android page said:
GROUP_VISIBLE - Flag indicating if the contacts belonging to this group should be visible in any user interface.
GROUP_IS_READ_ONLY - The "read-only" flag: "0" by default, "1" if the row cannot be modified or deleted except by a sync adapter. See ContactsContract.CALLER_IS_SYNCADAPTER.
Thanks!
So, to continue from the comments section, the answer is that your input values are ok, and persisted as requested.
However, the Contacts app (or any other app that reads contacts) can just ignore the values at GROUP_VISIBLE and display all contacts on the phone.
Usually apps provide some filter capabilities to the user, so the user can choose if she wants to see only contacts in visible groups, all contacts on the phone, or a specific group.
If you query for contacts using the IN_VISIBLE_GROUP selection, then you should not get the contacts created under your group in the cursor response.

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.

get user group description and name in liferay

I want to get the user group description as well the name of logged-in user in portlet.
I am able to get the logged-in user object using:
ThemeDisplay td = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
User user = td.getUser();
Please help me out with how to get the logged-in user's group.
These user groups are coming from ldap and mapped in liferay DB UserGroup.
Thanks in advance.
As you have the user object, you can get full name of user by using
user.getFullName()
for getting the user group description, call the following method, which will give you the list of Groups. which belongs to user.
List <Group> grpList = GroupLocalServiceUtil.getUserGroups(userId);
Iterate the list to get the groupId's. Pass group Id to following method.
Group grp = GroupLocalServiceUtil.getGroup(groupId)
You can get group Description using
String grpDisc = grp.getDescription();
Hope this is what you are looking for.

Categories

Resources