How to get users from Active Directory using Unboundid LDAP SDK? - active-directory

I need to get users from Active Directory.
According to many places include MSDN
https://msdn.microsoft.com/en-us/library/ms677643%28v=vs.85%29.aspx
the correct query is this (&(objectClass=user)(objectCategory=person)).
Unfortunately, I was not able to create the query using Unboundid filters.
I have created the following filters:
Filter categoryFilter = Filter.createEqualityFilter("objectCategory","Person");
Filter objectFilter = Filter.createEqualityFilter("objectClass","user");
Filter searchFilter = Filter.createANDFilter(objectFilter, categoryFilter);
It does not return results.
When I looked into objectCategory of LDAP object I have found that it looks like the following:
CN=Person,CN=Schema,CN=Configuration,DC=…,DC=com
Therefore I have changed categoryFilter to the following:
Filter categoryFilter = Filter.createSubstringFilter("objectCategory", null, new String[]{"Person"}, null);
Unfortunately, I still do not get results.
Then I used the categoryFilter with the full objectCategory name:
Filter categoryFilter = Filter.createEqualityFilter("objectCategory","CN=Person,CN=Schema,CN=Configuration,DC=…,DC=com");
Only in the last case I get results.
How to make the filter more generic?
How to obtain the full objectCategory name from Active Directory?
I need to obtain CN=Person,CN=Schema,CN=Configuration,DC=…,DC=com for any Active Directory while I know that the objectCategory is Person.
Do you know other way to create filters for the query (&(objectClass=user)(objectCategory=person))?
Solution
(not mine therefore do not want to put in the answer)
I have created filter using the following string (sAMAccountType=805306368) and it works perfect:
Filter searchFilter = Filter.create("(sAMAccountType=805306368)");
Source: http://ldapwiki.com/wiki/Active%20Directory%20User%20Related%20Searches#section-Active+Directory+User+Related+Searches-AllUsers

Related

Query based on multiple filters in Firebase

I am working out the structure for a JSON database for an app like onlyFans. Basically, someone can create a club, then inside of that club, there are sections where the creator's posts are shown and another where the club members posts are shown. There is however a filter option where both can be seen.
In order to make option 1 below work, I need to be able to filter based on if isFromCreator=true and at the same time based on timstamp. How can I do this?
Here are the 2 I have written down:
ClubContent
CreatorID
clubID
postID: {isFromCreator: Bool}
OR
creatorPosts
postID: {}
MemeberPosts
postID: {}
Something like the below would be what I want:
ref.child("Content").child("jhTFin5npXeOv2fdwHBrTxTdWIi2").child("1622325513718")
.queryOrdered(byChild: "timestamp")
.queryLimited(toLast: 10)
.queryEqual(toValue: true, childKey: "isFromCreator")
I triedqueryEqual yet it did not return any of the values I know exist with the configuration I specified.
You can use additional resource locations within rules by referencing the parent/child directories specifically and comparing the val() of the respective node structure.
for example:
".write": "data.parent().child('postID').child('isFromCreator').val()"
Just be aware that Security Rules do not filter or process the data in the request, only allow or deny the requested operation.
You can read more about this from the relevant documentation:
https://firebase.google.com/docs/database/security/rules-conditions#referencing_data_in_other_paths
https://firebase.google.com/docs/database/security/core-syntax#rules-not-filters

Cakephp 3 - How to integrate external sources in table?

I working on an application that has its own database and gets user information from another serivce (an LDAP is this case, through an API package).
Say I have a tables called Articles, with a column user_id. There is no Users table, instead a user or set of users is retrieved through the external API:
$user = LDAPConnector::getUser($user_id);
$users = LDAPConnector::getUsers([1, 2, 5, 6]);
Of course I want retrieving data from inside a controller to be as simple as possible, ideally still with something like:
$articles = $this->Articles->find()->contain('Users');
foreach ($articles as $article) {
echo $article->user->getFullname();
}
I'm not sure how to approach this.
Where should I place the code in the table object to allow integration with the external API?
And as a bonus question: How to minimise the number of LDAP queries when filling the Entities?
i.e. it seems to be a lot faster by first retrieving the relevant users with a single ->getUsers() and placing them later, even though iterating over the articles and using multiple ->getUser() might be simpler.
The most simple solution would be to use a result formatter to fetch and inject the external data.
The more sophisticated solution would a custom association, and a custom association loader, but given how database-centric associations are, you'd probably also have to come up with a table and possibly a query implementation that handles your LDAP datasource. While it would be rather simple to move this into a custom association, containing the association will look up a matching table, cause the schema to be inspected, etc.
So I'll stick with providing an example for the first option. A result formatter would be pretty simple, something like this:
$this->Articles
->find()
->formatResults(function (\Cake\Collection\CollectionInterface $results) {
$userIds = array_unique($results->extract('user_id')->toArray());
$users = LDAPConnector::getUsers($userIds);
$usersMap = collection($users)->indexBy('id')->toArray();
return $results
->map(function ($article) use ($usersMap) {
if (isset($usersMap[$article['user_id']])) {
$article['user'] = $usersMap[$article['user_id']];
}
return $article;
});
});
The example makes the assumption that the data returned from LDAPConnector::getUsers() is a collection of associative arrays, with an id key that matches the user id. You'd have to adapt this accordingly, depending on what exactly LDAPConnector::getUsers() returns.
That aside, the example should be rather self-explanatory, first obtain a unique list of users IDs found in the queried articles, obtain the LDAP users using those IDs, then inject the users into the articles.
If you wanted to have entities in your results, then create entities from the user data, for example like this:
$userData = $usersMap[$article['user_id']];
$article['user'] = new \App\Model\Entity\User($userData);
For better reusability, put the formatter in a custom finder. In your ArticlesTable class:
public function findWithUsers(\Cake\ORM\Query $query, array $options)
{
return $query->formatResults(/* ... */);
}
Then you can just do $this->Articles->find('withUsers'), just as simple as containing.
See also
Cookbook > Database Access & ORM > Query Builder > Adding Calculated Fields
Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Custom Finder Methods

Ordering the solr search results based on the indexed fields

I have to order the search results from solr based on some fields which are already indexed.
My current api request is like this without sorting.
http://127.0.0.1:8000/api/v1/search/facets/?page=1&gender=Male&age__gte=19
And it gives the search results based on the indexed order. But I have to reorder this results based on the filed 'last_login' which is already indexed DateTimeField.
Here is my viewset
class ProfileSearchView(FacetMixin, HaystackViewSet):
index_models = [Profile]
serializer_class = ProfileSearchSerializer
pagination_class = PageNumberPagination
facet_serializer_class = ProfileFacetSerializer
filter_backends = [HaystackFilter]
facet_filter_backends = [HaystackFilter, HaystackFacetFilter]
def get_queryset(self, index_models=None):
if not index_models:
index_models = []
queryset = super(ProfileSearchView, self).get_queryset(index_models)
queryset = queryset.order_by('-created_at')
return queryset`
Here I have changed the default search order by 'created_at' value. But for the next request I have order based on the 'last_login' value. I have added a new parameter in my request like this
http://127.0.0.1:8000/api/v1/search/facets/?page=1&gender=Male&age__gte=19&sort='last_login'
but it gives me an error
SolrError: Solr responded with an error (HTTP 400): [Reason: undefined field sort]
How can I achieve this ordering possible? Please help me with a solution.
The URL you provided http://127.0.0.1:8000/api/v1/search/facets/ is not direct SOLR URL. It must be your middle-ware. Since you have tried the query directly against Solr and it works, the problem must be somewhere in middle-ware layer.
Try to print or monitor or check logs to see what URL the midde-ware actually generates and compare it to the valid URL you know works.

LDAP Filter, search contains (Active Directory)

I want find users from active directory where Objectsid = "x-xxx-xxxxxx-xxxxxxx-11060"
My search filter is :
(&(objectClass=user)(objectCategory=person)(Objectsid=*11060))
but no users are returned.
What is problem with my filter?
When I completely write Objectsid the user information return.
Even when change code to
(&(objectClass=user)(objectCategory=person)(Objectsid=*))
that should return all users, but no user are returned
LDAP is case-sensitive, and the proper spelling of that attribute you're trying to use is objectSid (not Objectsid) - so try this filter:
(&(objectClass=user)(objectCategory=person)(objectSid=*))

Search For All Locations In Active Dirrectory Via LDAP

I'm working in PL/SQL and searching LDAP ( with A.D defining the schema) for all locations. Right now I can apply a simple search and find all users. Each user has the address information via the following properties:
'physicalDeliveryOfficeName';
'streetAddress';
'l';--city
'st';--state
'postalCode';--zip code
However, I would like to search for all the locations separate from the search done for people. Is it possible to search Active directory to just find the locations(with out looking up each person) ? If so what would the search filter look like ? I tried objectClass=Physical-Location,DC=example,DC=com and didn't find any locations (beyond the schema) . I'm not sure if that's because there's a security issue, or its not possible to look up locations in that way.
What you have listed are attributes in AD. You can return attributes in searches and search for specific values but you'll always return the objects the attributes are attached to (in this case users). You're a little light on the details of how you're searching so I'll take a stab.
You can load just the location attributes you're looking for, be it State, City, etc.
var domain = "mydomain.com";
var dn = "CN=Users,DC=mydomain,DC=com";
var ldapSearchFilter = "(objectClass=user)";
var connection = new LdapConnection(domain);
var attributeList = new string[] { "physicalDeliveryOfficeName", "l", "st"};
try
{
var searchRequest =
new SearchRequest(dn, ldapSearchFilter,
SearchScope.OneLevel,
attributeList);
var searchResponse =
(SearchResponse)connection.SendRequest(searchRequest);
var locationList = (from SearchResultEntry entry in searchResponse.Entries
select entry.Attributes["physicalDeliveryOfficeName"][0].ToString())
.Distinct().ToList();
catch (Exception ex)
{
//Handle errors
}
One thing to keep in mind with this example. If the attributes aren't populated in AD, the WriteLine will throw an error when trying to read the attribute. If you are using some other search type (DirectorySearcher maybe) you should still be able to load just the attributes you want to get back.

Resources