Find a User by Email Address

Adrian Thompson Phillips picture Adrian Thompson Phillips · May 19, 2016 · Viewed 9.1k times · Source

I'm trying find out if an email address is already taken in my Azure AD B2C directory.

var token = await this.GetTokenAsync();

var client = new HttpClient();

var id = HttpUtility.UrlEncode("adrian_mydomain.com#EXT#@xxxxxxxxx.onmicrosoft.com");
////var id = HttpUtility.UrlEncode("[email protected]"); // This also fails.
////var id = HttpUtility.UrlEncode("adrian_mydomain.com#EXT#"); // This also fails.
////var id = "xxxx-xxxx-xxxxxxxx-xxxxxxxxxx"; // This also fails (user object id).

var resource = $"{this.graphConfig.GraphUri}/{this.graphConfig.Tenant}/users/{id}?api-version=1.6";
//// This line below works, it returns all the users, so I do know the token is good and the resource URI is valid, etc.
////var resource = $"{this.graphConfig.GraphUri}/{this.graphConfig.Tenant}/users?api-version=1.6";

var request = new HttpRequestMessage(HttpMethod.Get, resource);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();

I'm encoding my email address in the same way that I see my email address encoded when I get all users. I have a feeling I'm close, if it is even possible to query by email address.

Currently all the things I've tried either return a 400 or a 404. Does anyone know if there is a way to query by email address (sign in name)?

EDIT

On a similar theme, I'm also trying a query to change a user's password to no avail. I figure if I can get the query working for one, I can get it working on the other.

Answer

Karthikeyan VK picture Karthikeyan VK · Jul 3, 2017

Since it is a odata, you can query using odata syntax. Odata syntax here

var queryString = HttpUtility.ParseQueryString(string.Empty);
queryString["api-version"] = "1.6";
queryString["$filter"] = "signInNames/any(x:x/value eq '[email protected]')";

string url = "https://graph.windows.net/" + tenant + "/users"+ "?" + queryString;

$filter did the trick

queryString["$filter"] = "signInNames/any(x:x/value eq '[email protected]')";