2015-01-15

I was looking into the Office 365 apps for our projects, where we have to get the user properties for the logged in user from the Azure AD.  Just putting together some code and the article referenced, so that it will be helpful.

Articles:

The following code gets the current logged in user property using the graph api from the Office 365 application.

var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;<br>var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; <br>
string TenantIdClaimType = "http://schemas.microsoft.com/identity/claims/tenantid";<br>
string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value;<br>
string upn = HttpContext.Current.User.Identity.Name;<br>
Microsoft.IdentityModel.Clients.ActiveDirectoryAuthenticationContext ac = new Microsoft.IdentityModel.Clients.ActiveDirectoryAuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));<br>
// SettingsHelper.ClientId = "ClientId value  retrieved from the Azure AD"
// SettingsHelper.AppKey = "Keys for the registered application in the Azure AD"
ClientCredential cc = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey);<br>
AuthenticationResult result = ac.AcquireToken("https://graph.windows.net", cc);<br>
HttpClient client = new HttpClient();<br>
string requestUrl = String.Format(<br>
                                CultureInfo.InvariantCulture,<br>
                                "https://graph.windows.net/{0}/users/{1}?api-version=2013-11-08",<br>
                                HttpUtility.UrlEncode(tenantId), HttpUtility.UrlEncode(upn));<br>
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);<br>
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);<br>
HttpResponseMessage response = client.SendAsync(request).Result;<br>
User user = null; // Type "User" is a custom class with the userprofile properties<br>
if (response.IsSuccessStatusCode)<br>
{<br>
  string responseString = response.Content.ReadAsStringAsync().Result;<br>
  user = JsonConvert.DeserializeObject<User>(responseString);<br>
}

 

About the author 

Balamurugan Kailasam