microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
Libraries/Microsoft.Teams.Extensions/Microsoft.Teams.Extensions.Graph/ContextExtensions.cs
40lines · modecode
| 1 | using Microsoft.Graph; |
| 2 | using Microsoft.Teams.Api.Activities; |
| 3 | using Microsoft.Teams.Apps; |
| 4 | |
| 5 | namespace Microsoft.Teams.Extensions.Graph; |
| 6 | |
| 7 | public static class ContextExtensions |
| 8 | { |
| 9 | /// <summary> |
| 10 | /// Get user's graph client from the context. |
| 11 | /// </summary> |
| 12 | /// <typeparam name="TActivity">The activity type</typeparam> |
| 13 | /// <param name="context">The context object</param> |
| 14 | /// <returns>The graph client scoped to the user's token</returns> |
| 15 | /// <exception cref="InvalidOperationException">If the user token doesn't exist on the context. That is, if the user is not signed in.</exception> |
| 16 | public static GraphServiceClient GetUserGraphClient<TActivity>(this IContext<TActivity> context) where TActivity : IActivity |
| 17 | { |
| 18 | var userToken = context.UserGraphToken; |
| 19 | |
| 20 | if (userToken is null) |
| 21 | { |
| 22 | throw new InvalidOperationException("context.UserGraphToken is null. Ensure the user is signed in and the token is available in the context."); |
| 23 | } |
| 24 | |
| 25 | if (context.Extra.TryGetValue("UserGraphClient", out var client) && client is GraphServiceClient graphClient) |
| 26 | { |
| 27 | return graphClient; |
| 28 | } |
| 29 | |
| 30 | var userGraphTokenProvider = Azure.Core.DelegatedTokenCredential.Create((context, _) => |
| 31 | { |
| 32 | return new Azure.Core.AccessToken(userToken.ToString(), userToken.Token.ValidTo); |
| 33 | }); |
| 34 | |
| 35 | graphClient = new GraphServiceClient(userGraphTokenProvider); |
| 36 | context.Extra["UserGraphClient"] = graphClient; |
| 37 | |
| 38 | return graphClient; |
| 39 | } |
| 40 | } |