Skip to content

Instantly share code, notes, and snippets.

@cmatskas
Last active May 20, 2020 01:07
Show Gist options
  • Save cmatskas/8d94332af458a076675521867b14e4a9 to your computer and use it in GitHub Desktop.
Save cmatskas/8d94332af458a076675521867b14e4a9 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;
using Microsoft.Identity.Client;
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class GraphController : ControllerBase
{
private GraphClient graphClient;
public GraphController(GraphClient client)
{
graphClient = client;
}
[HttpGet]
public async Task<IEnumerable<object>> Get()
{
IEnumerable<User> users;
try
{
users = await graphClient.ServiceClient.Users.Request().GetAsync();
}
catch (MsalUiRequiredException ex)
{
graphClient.AuthenticationProvider.Token.ReplyForbiddenWithWwwAuthenticateHeader(graphClient.AuthenticationProvider.Scopes, ex);
throw ex;
}
catch (Exception)
{
throw;
}
return users.Select(x => new
{
name = x.DisplayName,
upn = x.UserPrincipalName,
mail = x.Mail,
city = x.City,
jobTitle = x.JobTitle,
image=x.Photo
});
}
[HttpGet("{upn}")]
public async Task<object> Get(string upn = "me")
{
User user;
try
{
if (upn.Equals("me"))
{
user = await graphClient.ServiceClient.Me.Request().GetAsync();
}
else
{
user = await graphClient.ServiceClient.Users[upn].Request().GetAsync();
}
}
catch (MsalUiRequiredException ex)
{
graphClient.AuthenticationProvider.Token.ReplyForbiddenWithWwwAuthenticateHeader(graphClient.AuthenticationProvider.Scopes, ex);
throw ex;
}
catch (Exception)
{
throw;
}
return new
{
name = user.DisplayName,
upn = user.UserPrincipalName,
mail = user.Mail,
city = user.City,
jobTitle = user.JobTitle,
image = user.Photo
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment