从O365中获取users到D365中
用D365 online可能会遇到这样的问题。 顾客需要获取O365 user的email address 发email使用。 但是又不想给这部分的users licenses。
那我们就可以通过graph api来获取这部分的users
我们首先可以通过 graph explorer来检查下索要获取的restful api
https://developer.microsoft.com/en-us/graph/graph-explorer
在我们开始写代码获取O365用户之前, 我们需要在portal.azure中注册一个application。
首先,我们需要register application并且需要add a permission。
在这里要注意了, 我们需要选择application permissions 而不是delegated permission。
两者区别在于application permission在赋予admin consent 权限之后不需要再次有弹出框登录。而delegated permission则需要每次都有弹出框来登录。
其次,我们要找到User.Read.All 并且选中
最后,我们需要给与User.Read.All 权限
这里需要注意的是 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是这样的