Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Microsoft.Graph" Version="3.35.0" />
<PackageReference Include="Microsoft.Identity.Web" Version="1.14.1" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
using System;
using Microsoft.Graph;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GraphExplorerAppModeService.Interfaces
{
interface IGraphAppAuthProvider
public interface IGraphAppAuthProvider
{
GraphServiceClient GetAuthenticatedGraphClient(string accessToken);
}
}
14 changes: 11 additions & 3 deletions GraphExplorerAppModeService/Services/GraphAppAuthProvider.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
using GraphExplorerAppModeService.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Graph;
using Microsoft.Identity.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

Expand All @@ -11,9 +14,14 @@ namespace GraphExplorerAppModeService.Services
{
public class GraphAppAuthProvider : IGraphAppAuthProvider
{
public GraphAppAuthProvider(IConfiguration configuration)
{

}
public GraphServiceClient GetAuthenticatedGraphClient(string accessToken) =>
new GraphServiceClient(new DelegateAuthenticationProvider(
async requestMessage =>
{
// Append the access token to the request
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
}));
}

}
150 changes: 128 additions & 22 deletions GraphWebApi/Controllers/GraphExplorerAppModeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,79 +2,185 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using GraphExplorerAppModeService.Interfaces;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Identity.Web;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.Graph;
using System.Net;
using Microsoft.Identity.Client;
using System.Threading;
using Microsoft.Extensions.Primitives;
using GraphExplorerAppModeService.Services;
using GraphExplorerAppModeService.Interfaces;
using Microsoft.Extensions.Configuration;

namespace GraphWebApi.Controllers
{
[ApiController]
public class GraphExplorerAppModeController : ControllerBase
{
private readonly ITokenAcquisition tokenAcquisition;
public GraphExplorerAppModeController(ITokenAcquisition tokenAcquisition)
private readonly IGraphAppAuthProvider _graphClient;
private readonly ITokenAcquisition _tokenAcquisition;

private readonly IConfiguration _config;

public GraphExplorerAppModeController(IConfiguration configuration, ITokenAcquisition tokenAcquisition, IGraphAppAuthProvider graphServiceClient)
{
this.tokenAcquisition = tokenAcquisition;
this._graphClient = graphServiceClient;
this._tokenAcquisition = tokenAcquisition;
this._config = configuration;
}
[Route("api/[controller]/{*all}")]
[Route("graphproxy/{*all}")]
[HttpGet]
public async Task<IActionResult> GetAsync(string all, [FromHeader] string Authorization)
[AuthorizeForScopes(Scopes = new[] { "https://graph.microsoft.com/.default" })]
public async Task<IActionResult> GetAsync(string all)
{
return await ProcessRequestAsync("GET", all, null, Authorization).ConfigureAwait(false);
return await this.ProcessRequestAsync("GET", all, null, _config.GetSection("AzureAd").GetSection("TenantId").Value).ConfigureAwait(false);
}

[Route("api/[controller]/{*all}")]
[Route("graphproxy/token/{tenantId}")]
[HttpGet]
[AuthorizeForScopes(Scopes = new[] { "https://graph.microsoft.com/.default" })]
public async Task<string> GetTokenAsync(string tenantId)
private async Task<string> GetTokenAsync(string tenantId)
{
// Acquire the access token.
string scopes = "https://graph.microsoft.com/.default";
return await tokenAcquisition.GetAccessTokenForAppAsync(scopes, tenantId, null);

return await _tokenAcquisition.GetAccessTokenForAppAsync(scopes, tenantId, null);
}


[Route("api/[controller]/{*all}")]
[Route("graphproxy/{*all}")]
[HttpPost]
public async Task<IActionResult> PostAsync(string all, [FromBody] object body, [FromHeader] string Authorization)
[AuthorizeForScopes(Scopes = new[] { "https://graph.microsoft.com/.default" })]
public async Task<IActionResult> PostAsync(string all, [FromBody] object body)
{
return await ProcessRequestAsync("POST", all, body, Authorization).ConfigureAwait(false);
return await ProcessRequestAsync("POST", all, body, _config.GetSection("AzureAd").GetSection("TenantId").Value).ConfigureAwait(false);
}

[Route("api/[controller]/{*all}")]
[Route("graphproxy/{*all}")]
[HttpDelete]
public async Task<IActionResult> DeleteAsync(string all, [FromHeader] string Authorization)
{
return await ProcessRequestAsync("DELETE", all, null, Authorization).ConfigureAwait(false);
return await ProcessRequestAsync("DELETE", all, null, _config.GetSection("AzureAd").GetSection("TenantId").Value).ConfigureAwait(false);
}

[Route("api/[controller]/{*all}")]
[Route("graphproxy/{*all}")]
[HttpPut]
public async Task<IActionResult> PutAsync(string all, [FromBody] object body, [FromHeader] string Authorization)
[AuthorizeForScopes(Scopes = new[] { "https://graph.microsoft.com/.default" })]
public async Task<IActionResult> PutAsync(string all, [FromBody] object body)
{
return await ProcessRequestAsync("PUT", all, body, _config.GetSection("AzureAd").GetSection("TenantId").Value).ConfigureAwait(false);
}

private string GetBaseUrlWithoutVersion(GraphServiceClient graphClient)
{
var baseUrl = graphClient.BaseUrl;
var index = baseUrl.LastIndexOf('/');
return baseUrl.Substring(0, index);
}

public class HttpResponseMessageResult : IActionResult
{
return await ProcessRequestAsync("PUT", all, body, Authorization).ConfigureAwait(false);
private readonly HttpResponseMessage _responseMessage;

public HttpResponseMessageResult(HttpResponseMessage responseMessage)
{
_responseMessage = responseMessage; // could add throw if null
}

public async Task ExecuteResultAsync(ActionContext context)
{
context.HttpContext.Response.StatusCode = (int)_responseMessage.StatusCode;

foreach (var header in _responseMessage.Headers)
{
context.HttpContext.Response.Headers.TryAdd(header.Key, new StringValues(header.Value.ToArray()));
}

context.HttpContext.Response.ContentType = _responseMessage.Content.Headers.ContentType.ToString();

using (var stream = await _responseMessage.Content.ReadAsStreamAsync())
{
await stream.CopyToAsync(context.HttpContext.Response.Body);
await context.HttpContext.Response.Body.FlushAsync();
}
}
}

[Route("api/[controller]/{*all}")]
[Route("graphproxy/{*all}")]
[HttpPatch]
public async Task<IActionResult> PatchAsync(string all, [FromBody] object body, [FromHeader] string Authorization)
[AuthorizeForScopes(Scopes = new[] { "https://graph.microsoft.com/.default" })]
public async Task<IActionResult> PatchAsync(string all, [FromBody] object body)
{
return await ProcessRequestAsync("PATCH", all, body, _config.GetSection("AzureAd").GetSection("TenantId").Value).ConfigureAwait(false);
}

private async Task<IActionResult> ProcessRequestAsync(string method, string all, object content, string tenantId)
{
return await ProcessRequestAsync("PATCH", all, body, Authorization).ConfigureAwait(false);
GraphServiceClient _graphServiceClient = _graphClient.GetAuthenticatedGraphClient(GetTokenAsync(tenantId).Result.ToString());

var qs = HttpContext.Request.QueryString;

var url = $"{GetBaseUrlWithoutVersion(_graphServiceClient)}/{all}{qs.ToUriComponent()}";

var request = new BaseRequest(url, _graphServiceClient, null)
{
Method = method,
ContentType = HttpContext.Request.ContentType,
};

var neededHeaders = Request.Headers.Where(h => h.Key.ToLower() == "if-match" || h.Key.ToLower() == "consistencylevel").ToList();
if (neededHeaders.Count() > 0)
{
foreach (var header in neededHeaders)
{
request.Headers.Add(new HeaderOption(header.Key, string.Join(",", header.Value)));
}
}

var contentType = "application/json";
try
{
using (var response = await request.SendRequestAsync(content?.ToString(), CancellationToken.None, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false))
{
response.Content.Headers.TryGetValues("content-type", out var contentTypes);

contentType = contentTypes?.FirstOrDefault() ?? contentType;

var byteArrayContent = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
Console.WriteLine(byteArrayContent);
return new HttpResponseMessageResult(ReturnHttpResponseMessage(HttpStatusCode.OK, contentType, new ByteArrayContent(byteArrayContent)));
}
}
catch (ServiceException ex)
{
return new HttpResponseMessageResult(ReturnHttpResponseMessage(ex.StatusCode, contentType, new StringContent(ex.Error.ToString())));
}
}

private async Task<IActionResult> ProcessRequestAsync(string method, string all, object content, string Authorizaton)
private static HttpResponseMessage ReturnHttpResponseMessage(HttpStatusCode httpStatusCode, string contentType, HttpContent httpContent)
{

return Ok();
var httpResponseMessage = new HttpResponseMessage(httpStatusCode)
{
Content = httpContent
};

try
{
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
}
catch
{
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}

return httpResponseMessage;
}
}
}
2 changes: 2 additions & 0 deletions GraphWebApi/GraphWebApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,12 @@
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="5.0.7" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.7" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="5.0.0" />
<PackageReference Include="Microsoft.Graph" Version="3.35.0" />
<PackageReference Include="Microsoft.Identity.Web" Version="1.14.1" />
<PackageReference Include="Microsoft.Identity.Web.MicrosoftGraph" Version="1.14.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.10.8" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" />
<PackageReference Include="MySql.Data" Version="8.0.25" />
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="3.1.0" />
Expand Down
4 changes: 4 additions & 0 deletions GraphWebApi/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
using System.Threading.Tasks;
using Microsoft.Identity.Web;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using GraphExplorerAppModeService.Services;
using GraphExplorerAppModeService.Interfaces;

namespace GraphWebApi
{
Expand All @@ -51,6 +53,7 @@ public void ConfigureServices(IServiceCollection services)
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration, "AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(Configuration.GetSection("GraphV1"))
.AddInMemoryTokenCaches();
services.AddDistributedMemoryCache();
services.AddAuthentication(option =>
Expand Down Expand Up @@ -103,6 +106,7 @@ public void ConfigureServices(IServiceCollection services)

services.AddMemoryCache();
services.AddSingleton<ISnippetsGenerator, SnippetsGenerator>();
services.AddSingleton<IGraphAppAuthProvider, GraphAppAuthProvider>();
services.AddSingleton<IFileUtility, AzureBlobStorageUtility>();
services.AddSingleton<IPermissionsStore, PermissionsStore>();
services.AddSingleton<ISamplesStore, SamplesStore>();
Expand Down