Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify if user account exists in Azure Active Directory

I need to send an email to users from an ASP.NET Core 2 application, following some business rules. However, I need to ensure that the account the email is being sent to actually exists (for some reason, it may be that the account stopped being valid). The customer is using Azure Active Directory, so I need to query AAD somehow so it lets me know whether the account exists or not.

So far I have been looking for Microsoft Graph as a way to do this, however every example I have seen so far requires prior authentication and use a delegate authentication mechanism. I don't want my users having to authenticate nor to prompt the authentication screen.

Given this situation, what would you recommend using? If you can also point me to an example, that would be great. Thanks!

like image 856
Fernando Gómez Avatar asked Nov 20 '25 02:11

Fernando Gómez


1 Answers

You don't really need to throw/catch exception for every invalid user as you're doing in current code. I have nothing against exception handling in general for other reasons but to see if the user exists or not you can try using Filter.

So your graph query could look like -

https://graph.microsoft.com/v1.0/users?$filter=startswith(userPrincipalName,'[email protected]')

I have shown startswith here becuase eq didn't work for me in a quick trial. Although I would recommend two things:

  • Go through Microsoft documentation on Filters here and see what works best for your requirements - Use query parameters to customize responses with Microsoft Graph
  • Play a little bit with different queries in Microsoft Graph Explorer it's very simple and easy to use.

Here is a modified version for your code.

Note that I'm checking for the collection count to be > 0 and not checking for it to be null, as even in case user is not found the UsersCollectionPage was not null for my test run.

using Microsoft.Identity.Client;
using Microsoft.Graph.Auth;
using Microsoft.Graph;
...

private async Task<bool> ValidateAccounts(string accounts) {
    var confidentialClientApplication = ConfidentialClientApplicationBuilder
        .Create("clientId here")
        .WithTenantId("tokenId here")
        .WithClientSecret("secret here")
        .Build();
    var authProvider = new ClientCredentialProvider(confidentialClientApplication);
    var graphClient = new GraphServiceClient(authProvider);

    var valid = true;
    try {
        foreach (var account in accounts.Split(';')) {
            var user = await graphClient.Users.Request().Filter("startswith(userPrincipalName, '" + account + "')").GetAsync();

            if (user.Count <= 0) {
                valid = false;
                break;
            }
        }
    } catch (ServiceException ex) {
        valid = false;
    }

    return valid;
}

On a side note, I'm not not sure of your requirements but you could probably get creative by combining multiple user names in single query and then checking for result counts or other propertes. You could use or between multiple criteria or probably use any operator. I haven't really tried this out though.

like image 139
Rohit Saigal Avatar answered Nov 22 '25 16:11

Rohit Saigal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!