Get user information of Azure Active Directory account using Microsoft Graph API

Took a token at sign in using the ‘authorization code’ grant type authentication flow in the previous article. So the token has the ‘user.read’ permission. Use the token, this article describes how to take user information of the Azure Active Directory account.

>>The code sample of this article

・Setting configuration for development environment

As first, download the code sample, restore packages and run debug done, then modify ‘Sign In’ action in the ‘Account’ controller of [Controllers] folder at the Solution Explorer to usable for the development environment.

using Microsoft.AspNetCore.Mvc;

namespace React.Sample.Webpack.CoreMvc.Controllers
{
  public class AccountController : Controller
    {
    [Route("Account/SignIn")]
    [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
    public void SignIn()
    {
      var tenant = "__YOUR TENANT__";//this grant_type allows common
      var clientId = "__APP CLIENT ID__";
      var redirectUri = "http://localhost:9457/home";
      Response.Redirect("https://login.microsoftonline.com/" + tenant 
        + "/oauth2/v2.0/authorize?client_id=" + clientId + "&redirect_uri=" 
        + redirectUri + "&grant_type=implicit&response_type=code&scope=User.Read");
    }
  }
}

Modify lines of the variable ‘tenant’ and ‘clientId’ to useable for the development environment(11th line and 12th line).

And open ‘Index’ action in the ‘Home’ controller of [Controllers] folder at the Solution Explorer, put a breakpoint at the 45th line. Then run debug and confirm acquiring ‘code’ and ‘state’ variables.

・Get User Information

Return to the [Home] controller of the [Controllers] folder at the Solution Explorer, insert code below before the line of putting the ‘signIn’ variable to the ‘ViewBag.IsSignin’ container at the [Index] action.

if (signIn) accountName = new AccessGraph().GetUser(token);
if (!string.IsNullOrEmpty(accountName)) 
{
  //Regist '髙尾 哲朗(Tetsuro Takao)' as Azure Active Directory account.
  accountName = string.Join("", Regex.Matches(accountName, @"[a-z | A-Z]*")).Trim();
}
ViewBag.AccountName = accountName;

Insert code below to create the ‘GetUser’ method in the ‘AccessGraph’ class.

public string GetUser(string token)
{
    string result = string.Empty;
    MSGraphUser user = null;
    var url = $"https://graph.microsoft.com/v1.0/me/";
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
        var res = httpClient.GetAsync(url).Result;
        string resultJson = res.Content.ReadAsStringAsync().Result;
        if (res.IsSuccessStatusCode)
        {
            user = JsonConvert.DeserializeObject(resultJson);
            result = user.displayName;
        }
    }
    return result;
}

public class MSGraphUser
{
    public string displayName { get; set; }
    public string surname { get; set; }
    public string givenName { get; set; }
    public string id { get; set; }
    public string userPrincipalName { get; set; }
    public List businessPhones { get; set; }
    public string jobTitle { get; set; }
    public string mail { get; set; }
    public string mobilePhone { get; set; }
    public string officeLocation { get; set; }
    public string preferredLanguage { get; set; }
}

・Exchange a view when sign in and sign out

At the last, Open the ‘_Layout.cshtml’ in [Shared] folder of [Views] folder to modify a view. Modify like the below code as wrap the [a] tag of the ‘sign in’ part.

<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="col-md-3"><span>@ViewBag.Title</span></div>
        <div class="col-md-5">Menu items</div>
        <span class="col-md-3">
        @if (ViewBag.IsSignin)
        {
            <span>@ViewBag.AccountName</span>
        }
        else
        {
            <a href="/Account/SignIn" style="text-decoration: none;margin:0px;">
            	...
            </a>
        }
        </span>
        <div class="col-md-1"><span>@ViewBag.Message</span></div>
    </div>
</div>

>>The code sample of this article

About takao

I'm Microsoft MVP since June 2010.