-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProtectedApiCallHelper.cs
More file actions
68 lines (60 loc) · 2.73 KB
/
ProtectedApiCallHelper.cs
File metadata and controls
68 lines (60 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace MyAadFunction
{
/// <summary>
/// Helper class to call a protected API and process its result
/// </summary>
public class ProtectedApiCallHelper
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="httpClient">HttpClient used to call the protected API</param>
public ProtectedApiCallHelper(HttpClient httpClient)
{
HttpClient = httpClient;
}
protected HttpClient HttpClient { get; private set; }
/// <summary>
/// Calls the protected web API and processes the result
/// </summary>
/// <param name="webApiUrl">URL of the web API to call (supposed to return Json)</param>
/// <param name="accessToken">Access token used as a bearer security token to call the web API</param>
/// <param name="processResult">Callback used to process the result of the call to the web API</param>
public async Task<JObject> CallWebApiAndProcessResultASync(string webApiUrl, string accessToken)
{
if (!string.IsNullOrEmpty(accessToken))
{
var defaultRequestHeaders = HttpClient.DefaultRequestHeaders;
if (defaultRequestHeaders.Accept == null || !defaultRequestHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
JObject result = JsonConvert.DeserializeObject(json) as JObject;
return result;
}
else
{
string content = await response.Content.ReadAsStringAsync();
// Note that if you got reponse.Code == 403 and reponse.content.code == "Authorization_RequestDenied"
// this is because the tenant admin as not granted consent for the application to call the Web API
throw new Exception($"Failed to call the web API: {response.StatusCode}\nContent: {content}");
}
}
return null;
}
}
}