正在从 Azure Active Directory Graph Api 迁移到 Microsoft Graph Api

migrating from Azure Active Directory Graph Api to Microsoft Graph Api

我有一个正在登录的应用程序,使用 SSO office 365 对用户进行身份验证。我还调用 azure 活动目录图 api 来提取组织中所有用户的列表。我想停止使用 azure 活动目录图 api(因为它从 2/2019 开始被弃用)并移至 microsoft-graph api。如果我使用 Microsoft Graph 来拉取用户,我是否还必须使用 diff 方式(不是 Azure)进行身份验证?

这是我在启动文件中的当前授权码:

 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
                }
            });

    }

在图形调用中:

 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);

            }
        }

//更新:我能够像这样更新代码以使用 SOAP Microsoft Graph API:

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;
    }
}

Microsoft Graph API 也受 Azure AD 保护。因此,基本上,您只需向在 Azure AD 中注册的应用程序添加并授予必要的 Graph API 权限。

之后,您可以通过添加授权header来调用Microsoft Graph API。