Cyber
Cyber

Reputation: 5000

Azure AD: How to access Azure AD Graph API without using any library

I have developed a asp.net MVC 4 project .Currently i am planning to access Azure Graph API to get AD User data (access navigation properties of user , Ref link :Azure Rest API Reference ).

I have checked Azure AD Graph helper Library , but using this i am not able to access Navigation propery (ie: accessing manager property of User)

Any help is appreciated.

Upvotes: 0

Views: 1237

Answers (2)

Sergey Morozenko
Sergey Morozenko

Reputation: 171

By default not all navigation properties would be loaded when you are getting some entity (in our case 'User'). You should use Expand(..). Below I give an example how to assign Manager to User and how to get User's Manager navigation property (some infrastructure nuances omitted):

public async Task<Result> AssingUserManager(string userUpn, string managerUpn)
{
    try
    {
        var user = (AD.User)await ADClient.Users
            .Where(x => x.UserPrincipalName == userUpn)
            .ExecuteSingleAsync();

        var manager = (AD.User)await ADClient.Users
            .Where(x => x.UserPrincipalName == managerUpn)
            .ExecuteSingleAsync();

        user.Manager = manager;

        await manager.UpdateAsync();
        return Result.Ok();
    }
    catch (Exception ex)
    {
        return Result.Fail(new Error("Failed to assign manager", null, ex));
    }
}

public async Task<Result<User>> GetUserManager(string upn)
{
    try
    {
        var user = (AD.User)await ADClient.Users
                    .Where(x => x.UserPrincipalName == upn)
                    .Expand(x => x.Manager)
                    .ExecuteSingleAsync();

        var manager = user.Manager as AD.User;
        if (manager != null)
        {
            return Result.Ok(ConvertToModel(manager));
        }

        return Result.Fail<User>(new Error("Manager not found for specified user", null));
    }
    catch (Exception ex)
    {
        return Result.Fail<User>(new Error("Failed to get user's manager", null, ex));
    }
}

Also, notice that when I update the graph I do so by calling UpdateAsync on the user who is being assigned as the manager and not the user whose Manager property is being set (taken from this source)

Upvotes: 1

vibronet
vibronet

Reputation: 7394

You can easily hit the Graph directly via HttpClient or any other generic http request generation class. You just need to stick with OData conventions for accessing specific entities and filter your results. For some common queries you can try directly without any Graph library take a look at http://msdn.microsoft.com/en-us/library/azure/jj126255.aspx

Upvotes: 0

Related Questions