Skip to content

Instantly share code, notes, and snippets.

@ashelopukho
Created March 2, 2023 11:16
Show Gist options
  • Save ashelopukho/5b00944c7744ebb4f9baa348e86f7e0e to your computer and use it in GitHub Desktop.
Save ashelopukho/5b00944c7744ebb4f9baa348e86f7e0e to your computer and use it in GitHub Desktop.
Asp.net WebApi + GraphServiceClient v5
public static class GraphClientExtensions
{
public static IServiceCollection AddMicrosoftGraphClient(this IServiceCollection services)
{
services.AddScoped(sp =>
{
var tokenAcquisition = sp.GetRequiredService<ITokenAcquisition>();
var authenticationProvider = new BaseBearerTokenAuthenticationProvider(new TokenProvider(tokenAcquisition));
var graphServiceClient = new GraphServiceClient(authenticationProvider);
return graphServiceClient;
});
return services;
}
}
public class TokenProvider : IAccessTokenProvider
{
private readonly ITokenAcquisition _tokenAcquisition;
public TokenProvider(ITokenAcquisition tokenAcquisition)
{
_tokenAcquisition = tokenAcquisition;
}
public async Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object> additionalAuthenticationContext = default,
CancellationToken cancellationToken = default)
{
var token = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { "User.Read" });
return token;
}
public AllowedHostsValidator AllowedHostsValidator { get; }
}
@ashelopukho
Copy link
Author

Use in Program.cs:
builder.Services.AddMicrosoftGraphClient();

@mmcossu
Copy link

mmcossu commented Apr 28, 2023

Hi @ashelopukho, sorry, I might be missing something.
Is 'builder' a Microsoft.AspNetCore.Builder.WebApplicationBuilder instance?
So are you saying that Program has the same initialization of a Web Api 2 application?

@ashelopukho
Copy link
Author

@mmcossu, in this gist example - yes. But it's just for example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment