-
Notifications
You must be signed in to change notification settings - Fork 25
/
DefaultController.cs
64 lines (49 loc) · 1.94 KB
/
DefaultController.cs
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
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace authenticated.Controllers
{
[Route("")]
public class DefaultController : ControllerBase
{
private readonly IHttpClientFactory _clientFactory;
public DefaultController(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
[HttpGet]
public async Task<IActionResult> GetAsync()
{
var url = Environment.GetEnvironmentVariable("URL");
if (url == null)
{
return BadRequest("No URL defined");
}
var idToken = await GetIdToken(url);
if (idToken == null)
{
return BadRequest("No id token could be fetched");
}
var content = await MakeAuthRequest(idToken, url);
return Ok("Second service says: " + content);
}
private async Task<string> GetIdToken(string targetUrl)
{
var httpClient = _clientFactory.CreateClient();
var metadataUrl = $"http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience={targetUrl}";
var request = new HttpRequestMessage(HttpMethod.Get, metadataUrl);
request.Headers.Add("Metadata-Flavor", "Google");
var response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
private async Task<string> MakeAuthRequest(string idToken, string url)
{
var httpClient = _clientFactory.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Authorization", "Bearer " + idToken);
var response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
}