從O365中獲取users到D365中

用D365 online可能會遇到這樣的問題。  顧客須要獲取O365 user的email address 發email使用。 可是又不想給這部分的users licenses。 web

那咱們就能夠經過graph api來獲取這部分的usersjson

 

咱們首先能夠經過 graph explorer來檢查下索要獲取的restful apiwindows

https://developer.microsoft.com/en-us/graph/graph-explorerapi

 

 

 

 

在咱們開始寫代碼獲取O365用戶以前, 咱們須要在portal.azure中註冊一個application。restful

首先,咱們須要register application而且須要add a permission。app

在這裏要注意了, 咱們須要選擇application permissions 而不是delegated permission。dom

二者區別在於application permission在賦予admin consent 權限以後不須要再次有彈出框登陸。而delegated permission則須要每次都有彈出框來登陸。post

 

 

 

 其次,咱們要找到User.Read.All 而且選中ui

 

 

最後,咱們須要給與User.Read.All 權限url

 

 

 

 

這裏須要注意的是 Application ID, Directory ID 和 Secret Key是須要的

 

 

 

 接下來咱們就須要寫一個接口。

咱們能夠把這個接口用Microsoft flow天天凌晨call 作O365 users  同步。

                var tenant = "";
                var clientId = "";
                var secret = "";

                var tokenAuth = "https://login.microsoftonline.com/" + tenant + "/oauth2/v2.0/token";
                var authStr = "&client_id=" + clientId
                                + "&client_secret=" + HttpUtility.UrlEncode(secret)
                                + "&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&grant_type=client_credentials";
                HttpContent content = new StringContent(authStr, Encoding.UTF8, "application/x-www-form-urlencoded");
                HttpClient httpClient = new HttpClient();
                var httpClientResponse = httpClient.PostAsync(tokenAuth, content).Result;
                var contents = httpClientResponse.Content.ReadAsStringAsync().Result;

                TokenResult tokenResult = JsonConvert.DeserializeObject<TokenResult>(contents);
                var query = "https://graph.microsoft.com/v1.0/users/";

                using (var client = new HttpClient())
                {using (var request = new HttpRequestMessage(HttpMethod.Get, query))
                    {
                        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);

                        using (var response = client.SendAsync(request).GetAwaiter().GetResult())
                        {if (response.IsSuccessStatusCode)
                            {
                                var jsonString = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                                var jo = JsonConvert.DeserializeObject<JObject>(jsonString);
                                var ja = JsonConvert.DeserializeObject<JArray>(jo["value"].ToString());
                                if (ja.Count != 0)
                                {
                                    for (int i = O365UsersIndexNo; i < ja.Count; i++)
                                    {
                                        JToken item = ja[i];
                                        var displayName = item["displayName"].ToString();
                                        var domainName = item["userPrincipalName"].ToString();

                                        var account = ConfigurationManager.AppSettings["UserName"];
                                        var password = ConfigurationManager.AppSettings["Password"];
                                        var dhlResourceUrl = "https://xxx.crm5.dynamics.com/";
                                        var crmClientId = ConfigurationManager.AppSettings["ClientId"];
                                        var weburi = dhlResourceUrl + "api/data/v9.1/new_o365users";
                                        AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/common", false);
                                        AuthenticationResult result = authContext.AcquireToken(dhlResourceUrl, crmClientId, new UserCredential(account, password));
                                        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(weburi);

                                        req.Method = "post";
                                        req.Accept = "application/json";
                                        req.ContentType = "application/json; charset=utf-8";
                                        req.Headers.Add("OData-MaxVersion", "4.0");
                                        req.Headers.Add("OData-Version", "4.0");
                                        req.Headers.Set("Authorization", "Bearer " + result.AccessToken);
                                        req.Headers.Set("If-None-Match", "*");
                                        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

                                        var newO365User = new JObject();
                                        if (!string.IsNullOrEmpty(displayName) && !string.IsNullOrEmpty(domainName))
                                        {
                                            newO365User.Add("emailaddress", domainName);
                                            newO365User.Add("new_fullname", displayName);
                                            newO365User.Add("new_domainname", domainName);
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                        byte[] data = Encoding.UTF8.GetBytes(newO365User.ToString());
                                        Stream newStream = req.GetRequestStream();
                                        newStream.Write(data, 0, data.Length);
                                        newStream.Close();
                                        using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
                                        {
                                            StreamReader read = new StreamReader(res.GetResponseStream());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

 

若是咱們須要獲取當前新建立的O365 users, API query是這樣的

相關文章
相關標籤/搜索