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

 

(Visited 45 times, 1 visits today)

About the author 

Balamurugan Kailasam

Leave a Reply

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

2 Free Ebooks: How to govern Microsoft teams 

Download your 2 free Microsoft Teams governance Ebooks and learn the steps necessary to create a bullet-proof governance strategy.