Skip to content

Instantly share code, notes, and snippets.

@vman
Last active December 16, 2022 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vman/4350857ca03b08840653a96fc9c520a8 to your computer and use it in GitHub Desktop.
Save vman/4350857ca03b08840653a96fc9c520a8 to your computer and use it in GitHub Desktop.
public async Task<ActionResult> PostToTeams(string teamId, string channelId, string message)
{
var httpContext = _httpContextAccessor.HttpContext;
httpContext.Request.Headers.TryGetValue("Authorization", out StringValues assertion);
var idToken = assertion.ToString().Split(" ")[1];
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(idToken);
string tenantId = jwtSecurityToken.Claims.First(claim => claim.Type == "tid").Value;
GraphServiceClient graphServiceClient = await GetDelegatedGraphServiceClient(idToken, tenantId, new string[] {
"https://graph.microsoft.com/ChannelMessage.Send"
});
var chatMessage = new ChatMessage
{
Body = new ItemBody
{
Content = message
}
};
await graphServiceClient.Teams[teamId].Channels[channelId].Messages.Request().AddAsync(chatMessage);
return Ok();
}
private async Task<GraphServiceClient> GetDelegatedGraphServiceClient(string idToken, string tenantId, string[] scopes)
{
string clientId = _configuration.GetSection("AzureAd:ClientId")?.Value;
string clientSecret = _configuration.GetSection("AzureAd:AppSecret")?.Value;
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority($"https://login.microsoftonline.com/{tenantId}")
.Build();
UserAssertion assert = new UserAssertion(idToken);
var responseToken = await app.AcquireTokenOnBehalfOf(scopes, assert).ExecuteAsync();
string accessToken = responseToken.AccessToken.ToString();
var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
return Task.CompletedTask;
}));
return graphServiceClient;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment