Created
March 2, 2023 11:16
-
-
Save ashelopukho/5b00944c7744ebb4f9baa348e86f7e0e to your computer and use it in GitHub Desktop.
Asp.net WebApi + GraphServiceClient v5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} |
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?
@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
Use in Program.cs:
builder.Services.AddMicrosoftGraphClient();