0
votes

I have an application I am signing in to using SSO office 365 to authenticate the user. I am also calling the azure active directory graph api to pull a list of all users in the organization. I want to stop using the azure active directory graph api (since it is being deprecated as of 2/2019) and move over to microsoft-graph api. If I use microsoft graph to pull users, will I also have to authenticate with diff way (not Azure)?

this is my current auth code in startup file:

 public void ConfigureAuth(IAppBuilder app)
    {
        string strIssuers = ConfigurationManager.AppSettings["validIssuers"];
        string[] validIssuers = strIssuers.Split(',');

        app.UseWindowsAzureActiveDirectoryBearerAuthentication( 
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience = ConfigurationManager.AppSettings["ida:Audience"],
                    ValidIssuers = validIssuers
                }
            });

    }

in graph call:

 public async Task<List<User>> GetAdUsers(string tid, string path = "users")
        {
            var identity = HttpContext.Current.User.Identity as ClaimsIdentity;
            string email = identity?.Name;
            var selectvalues = "";//(path.ToLower() == "users" ? "$select=*" : "");
            List<User> tmpUsers;
            string skipToken;
            string skipTokenResult;
            int skipTokenIndex;
            string strAuth = "https://login.microsoftonline.com/" + tid + "/oauth2/v2.0/token";
            var client = ConfigurationManager.AppSettings["ida:Audience"];
            var secret = ConfigurationManager.AppSettings["clientSecret"];
            string clientId = client;
            string clientSecret = secret;
            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = null;
            AuthenticationContext _authContext = new AuthenticationContext(strAuth);
            Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential creds 
                = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientSecret);

            result = await _authContext.AcquireTokenAsync("https://graph.microsoft.com", creds);
            var _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);


            HttpResponseMessage Res = await _httpClient.GetAsync("https://graph.microsoft.com/v1.0/" + path + "?$top=999" + selectvalues);
            if (Res.IsSuccessStatusCode)
            {
                string strJson = Res.Content.ReadAsStringAsync().Result;
                JavaScriptSerializer json = new JavaScriptSerializer();
                RootObject rootObj = json.Deserialize<RootObject>(strJson);
                List<User> adUsers = rootObj.Value;
                var parseRes = JObject.Parse(strJson);
                bool stop = false;
                while (!stop)
                {

                    try
                    {
                        skipTokenResult = parseRes["@odata.nextLink"].Value<string>();
                        skipTokenIndex = skipTokenResult.IndexOf("skiptoken=");

                        skipToken = skipTokenResult.Substring(skipTokenIndex + 10, skipTokenResult.Length - skipTokenIndex - 10);
                        Res = await _httpClient.GetAsync("https://graph.microsoft.com/v1.0/" + path + "?$top=999&$skiptoken=" + skipToken + selectvalues);

                        if (Res.IsSuccessStatusCode)
                        {
                            strJson = Res.Content.ReadAsStringAsync().Result;
                            rootObj = json.Deserialize<RootObject>(strJson);
                            tmpUsers = rootObj.Value;
                            adUsers.AddRange(tmpUsers);
                            parseRes = JObject.Parse(strJson);
                        }
                        else
                        {
                            stop = true;
                        }
                    }
                    catch (ArgumentNullException)  // no skip token, stop looping !!!!
                    {
                        stop = true;
                    }
                }

                return adUsers;
            }
            else
            {
                //  return null;
                throw new Exception("GetAdUsers: Graph API failed for path: " + path + ", tid: " + tid + ". Reason: " + Res.ReasonPhrase);

            }
        }

//UPDATE: I was able to update the code to use SOAP Microsoft Graph API like this:

public GraphServiceClient AuthGraph(string tid, string groupId)
{
    try
    {
        var clientId =  ConfigurationManager.AppSettings["ida:Audience"];
        var clientSecret = ConfigurationManager.AppSettings["ida:clientSecret"];
        var tenantID = tid;

        IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
             .Create(clientId)
             //.WithRedirectUri(redirectUri)
             .WithTenantId(tenantID)
             .WithClientSecret(clientSecret)
             .Build();

        ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);


        GraphServiceClient graphClient = new GraphServiceClient(authProvider);
        return graphClient;
    }
    catch (Exception e)
    {
        throw e;
    }
}

public async Task<List<User>> GetAdUsers(string tid, string groupId)
{
    try
    {
        GraphServiceClient graphClient = AuthGraph(tid, groupId);

        var graphUsers = await graphClient.Users
            .Request()                   
            .GetAsync();

        List<User> users = graphUsers.Select(x => new User
        {
            Id = x.Id,
            BusinessPhones = x.BusinessPhones.ToArray(),
            DisplayName = x.DisplayName,
            GivenName = x.GivenName,
            JobTitle = x.JobTitle,
            Mail = x.Mail,
            MobilePhone = x.MobilePhone,
            OfficeLocation = x.OfficeLocation,
            PreferredLanguage = x.PreferredLanguage,
            Surname = x.Surname,
            UserPrincipalName = x.UserPrincipalName
        }
            ).ToList();

        if (!string.IsNullOrEmpty(groupId))
        {
            var membersInGroups = await GetNonSSOUsers(Globals.mghsTid, groupId);
            users.AddRange(membersInGroups);
        }

            return users;
    }
    catch(Exception ex)
    {
        _errService.LogError("UserController.Update", tid, ex.HResult, ex.ToString().Substring(0, Math.Min(ex.ToString().Length, Globals.maxErrDescLen)), "getAdUsersService", 1, DateTime.Now.ToString());
        throw ex;
    }
}


public async Task<List<User>> GetNonSSOUsers(string tid, string groupId)
{
    try
    {
        GraphServiceClient graphClient = AuthGraph(tid, groupId);

            var members = await graphClient.Groups[groupId].Members
                .Request()
                .GetAsync();

        List<User> users = new List<User>();

            //while (members.NextPageRequest != null && (members = await members.NextPageRequest.GetAsync()).Count > 0)
            //{
                foreach (var member in members)
                {
                    if (member is Microsoft.Graph.User)
                    {
                        var user = (Microsoft.Graph.User)member;

                    users.Add(new User
                    {
                        Id = user.Id,
                        BusinessPhones = user.BusinessPhones.ToArray(),
                        DisplayName = user.DisplayName,
                        GivenName = user.GivenName,
                        JobTitle = user.JobTitle,
                        Mail = user.Mail,
                        MobilePhone = user.MobilePhone,
                        OfficeLocation = user.OfficeLocation,
                        PreferredLanguage = user.PreferredLanguage,
                        Surname = user.Surname,
                        UserPrincipalName = user.UserPrincipalName
                    });
                    }
                }
           // }

        return users;
    }
    catch (Exception e)
    {
        throw e;
    }
}
1
Did you get an error?juunas

1 Answers

0
votes

The Microsoft Graph API is also protected under Azure AD. So, basically, you just need to add and grant necessary Graph API permissions to your application registered in Azure AD.

After that, you can call the Microsoft Graph API by adding an authorization header.