-
-
Save vman/4350857ca03b08840653a96fc9c520a8 to your computer and use it in GitHub Desktop.
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 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