Skip to content

Commit c7e17d9

Browse files
committed
added access denied
1 parent acef605 commit c7e17d9

6 files changed

Lines changed: 163 additions & 76 deletions

File tree

‎Services/SampleFunctions/GetAzureMapsToken.cs‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,19 @@
33
using Microsoft.AspNetCore.Http;
44
using Microsoft.AspNetCore.Mvc;
55
using Microsoft.Azure.Functions.Worker;
6-
using Microsoft.Extensions.Logging;
76

87
namespace SampleFunctions;
98

10-
public class GetAzureMapsToken(ILogger<GetAzureMapsToken> logger)
9+
public class GetAzureMapsToken()
1110
{
12-
private readonly ILogger<GetAzureMapsToken> _logger = logger;
11+
private static readonly string[] AllowedDomains = [
12+
"https://samples.azuremaps.com/",
13+
"https://demo.azuremaps.com/",
14+
"https://www.microsoft.com/",
15+
"https://microsoft.com/",
16+
"https://msmaps.azurewebsites.net/", // For local testing
17+
"http://localhost:58745/" // For local testing
18+
];
1319

1420
/// <summary>
1521
/// This token provider simplifies access tokens for Azure Resources. It uses the Managed Identity of the deployed resource.
@@ -29,13 +35,21 @@ public class GetAzureMapsToken(ILogger<GetAzureMapsToken> logger)
2935
];
3036

3137
[Function("GetAzureMapsToken")]
32-
public async Task<IActionResult> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req)
38+
public async Task<IActionResult> RunAsync(
39+
[HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req)
3340
{
34-
// Managed identities for Azure resources and Azure Maps
35-
// For the Web SDK to authorize correctly, you still must assign Azure role based access control for the managed identity
36-
// https://docs.microsoft.com/en-us/azure/azure-maps/how-to-manage-authentication
37-
AccessToken accessToken = await _TokenProvider.GetTokenAsync(new TokenRequestContext(_Scopes));
41+
// Check if the referer header is present and if the domain is allowed
42+
if (req.Headers.TryGetValue("Referer", out var referer) && AllowedDomains.Any(domain => referer.ToString().StartsWith(domain)))
43+
{
44+
// Managed identities for Azure resources and Azure Maps
45+
// For the Web SDK to authorize correctly, you still must assign Azure role based access control for the managed identity
46+
// https://docs.microsoft.com/en-us/azure/azure-maps/how-to-manage-authentication
47+
AccessToken accessToken = await _TokenProvider.GetTokenAsync(new TokenRequestContext(_Scopes));
48+
49+
return new OkObjectResult(accessToken.Token);
50+
}
3851

39-
return new OkObjectResult(accessToken.Token);
52+
// Retrun access denied if the referer domain is not allowed
53+
return new StatusCodeResult(StatusCodes.Status403Forbidden);
4054
}
4155
}
Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,30 @@
11
using Microsoft.AspNetCore.Http;
22
using Microsoft.AspNetCore.Mvc;
33
using Microsoft.Azure.Functions.Worker;
4-
using Microsoft.Extensions.Configuration;
5-
using Microsoft.Extensions.Logging;
64

75
namespace SampleFunctions;
86

9-
public class GetBingMapsKey(ILogger<GetBingMapsKey> logger)
7+
public class GetBingMapsKey()
108
{
11-
private readonly ILogger<GetBingMapsKey> _logger = logger;
9+
private static readonly string[] AllowedDomains = [
10+
"https://samples.bingmapsportal.com/",
11+
"https://www.microsoft.com/"
12+
];
1213

1314
[Function("GetBingMapsKey")]
14-
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req)
15+
public static IActionResult Run(
16+
[HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req)
1517
{
16-
// Get your Bing Maps key from https://www.bingmapsportal.com/
17-
var bingMapsKey = Environment.GetEnvironmentVariable("BING_MAPS_SUBSCRIPTION_KEY");
18+
// Check if the referer header is present and if the domain is allowed
19+
if (req.Headers.TryGetValue("Referer", out var referer) && AllowedDomains.Any(domain => referer.ToString().StartsWith(domain)))
20+
{
21+
// Bing Maps for Enterprise is now Azure Maps, get your key from https://azuremaps.com/
22+
var key = Environment.GetEnvironmentVariable("BING_MAPS_SUBSCRIPTION_KEY");
1823

19-
// Create a new response
20-
return new OkObjectResult(bingMapsKey);
24+
return new OkObjectResult(key);
25+
}
26+
27+
// Retrun access denied if the referer domain is not allowed
28+
return new StatusCodeResult(StatusCodes.Status403Forbidden);
2129
}
2230
}

‎Services/SampleFunctions/GetDataFromUrl.cs‎

Lines changed: 46 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,72 @@
11
using Microsoft.Azure.Functions.Worker;
22
using Microsoft.Azure.Functions.Worker.Http;
3-
using Microsoft.Extensions.Logging;
43
using System.Net;
54

65
namespace SampleFunctions;
76

8-
public class GetDataFromUrl(ILogger<GetDataFromUrl> logger)
7+
public class GetDataFromUrl()
98
{
10-
private readonly ILogger<GetDataFromUrl> _logger = logger;
9+
private static readonly string[] AllowedDomains = [
10+
"https://samples.azuremaps.com/",
11+
"https://www.microsoft.com/"
12+
];
1113

1214
private static readonly HttpClient _HttpClient = new();
1315

1416
[Function("GetDataFromUrl")]
15-
public static async Task<HttpResponseData> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req)
17+
public static async Task<HttpResponseData> RunAsync(
18+
[HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req)
1619
{
17-
var badRequest = req.CreateResponse(HttpStatusCode.BadRequest);
18-
19-
// Get the URL from the query string
20-
var url = Uri.UnescapeDataString(req.Query["url"]);
21-
if (string.IsNullOrEmpty(url))
20+
// Check if the referer header is present and if the domain is allowed
21+
if (req.Headers.TryGetValues("Referer", out var referer) && AllowedDomains.Any(domain => referer.ToString().StartsWith(domain)))
2222
{
23-
badRequest.WriteString("Please pass a valid URL address in the query string.");
24-
return badRequest;
25-
}
23+
var badRequest = req.CreateResponse(HttpStatusCode.BadRequest);
2624

27-
// Download the content from the URL
28-
var result = await _HttpClient.GetAsync(url);
25+
// Get the URL from the query string
26+
var url = Uri.UnescapeDataString(req.Query["url"]);
27+
if (string.IsNullOrEmpty(url))
28+
{
29+
badRequest.WriteString("Please pass a valid URL address in the query string.");
30+
return badRequest;
31+
}
2932

30-
if (!result.IsSuccessStatusCode)
31-
{
32-
badRequest.WriteString("The URL you specified was unable to download.");
33-
return badRequest;
34-
}
33+
// Download the content from the URL
34+
var result = await _HttpClient.GetAsync(url);
3535

36-
// Create a new response
37-
var response = req.CreateResponse(HttpStatusCode.OK);
36+
if (!result.IsSuccessStatusCode)
37+
{
38+
badRequest.WriteString("The URL you specified was unable to download.");
39+
return badRequest;
40+
}
3841

39-
// Copy the headers from the result to the response, except for the ones we want to skip
40-
foreach (var header in result.Headers)
41-
{
42-
if (!IsHeaderToSkip(header.Key))
42+
// Create a new response
43+
var response = req.CreateResponse(HttpStatusCode.OK);
44+
45+
// Copy the headers from the result to the response, except for the ones we want to skip
46+
foreach (var header in result.Headers)
4347
{
44-
response.Headers.Add(header.Key, header.Value.First());
48+
if (!IsHeaderToSkip(header.Key))
49+
{
50+
response.Headers.Add(header.Key, header.Value.First());
51+
}
4552
}
46-
}
4753

48-
// Set the 'Content-Type' header in the response
49-
response.Headers.Add("Content-Type", result.Content.Headers.ContentType.MediaType);
54+
// Set the 'Content-Type' header in the response
55+
response.Headers.Add("Content-Type", result.Content.Headers.ContentType.MediaType);
56+
57+
// Add the CORS header to the response
58+
response.Headers.Add("Access-Control-Allow-Origin", "*");
5059

51-
// Add the CORS header to the response
52-
response.Headers.Add("Access-Control-Allow-Origin", "*");
60+
// Copy the content from the result to the response
61+
var content = await result.Content.ReadAsByteArrayAsync();
62+
await response.Body.WriteAsync(content);
5363

54-
// Copy the content from the result to the response
55-
var content = await result.Content.ReadAsByteArrayAsync();
56-
await response.Body.WriteAsync(content);
64+
return response;
65+
}
5766

58-
return response;
67+
// Return access denied if the referer domain is not allowed
68+
var forbidden = req.CreateResponse(HttpStatusCode.Forbidden);
69+
return forbidden;
5970
}
6071

6172
private static bool IsHeaderToSkip(string headerName)
Lines changed: 45 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,68 @@
11
using Microsoft.AspNetCore.Http;
22
using Microsoft.AspNetCore.Mvc;
33
using Microsoft.Azure.Functions.Worker;
4-
using Microsoft.Extensions.Logging;
54
using SampleFunctions.Models;
65
using System.Globalization;
76
using System.Net.Http.Json;
87
using System.Text.Json;
98

109
namespace SampleFunctions;
1110

12-
public class GetGeolocation(ILogger<GetGeolocation> logger)
11+
public static class GeolocationService
1312
{
14-
private readonly ILogger<GetGeolocation> _logger = logger;
13+
private static readonly string[] AllowedDomains = [
14+
"https://samples.azuremaps.com/",
15+
"https://www.microsoft.com/"
16+
];
1517

16-
private static readonly HttpClient _HttpClient = new();
18+
private static readonly HttpClient HttpClient = new();
1719

1820
[Function("GetGeolocation")]
19-
public static async Task<IActionResult> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req)
21+
public static async Task<IActionResult> RunAsync(
22+
[HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req)
2023
{
21-
// Get the IP address from the query string
22-
var ip = req.Query["ip"];
23-
if (string.IsNullOrEmpty(ip))
24+
// Check if the referer header is present and if the domain is allowed
25+
if (req.Headers.TryGetValue("Referer", out var referer) && AllowedDomains.Any(domain => referer.ToString().StartsWith(domain)))
2426
{
25-
return new BadRequestObjectResult("Please pass a valid IP address on the query string.");
26-
}
27+
string ip = req.Query["ip"];
28+
if (string.IsNullOrWhiteSpace(ip))
29+
{
30+
return new BadRequestObjectResult("Please pass a valid IP address on the query string.");
31+
}
2732

28-
// Get the Azure Maps key from the environment variables
29-
var azureMapsKey = Environment.GetEnvironmentVariable("AZURE_MAPS_SUBSCRIPTION_KEY");
30-
var url = $"https://atlas.microsoft.com/geolocation/ip/json?subscription-key={azureMapsKey}&api-version=1.0&ip={ip}";
33+
string azureMapsKey = Environment.GetEnvironmentVariable("AZURE_MAPS_SUBSCRIPTION_KEY");
34+
if (string.IsNullOrWhiteSpace(azureMapsKey))
35+
{
36+
return new BadRequestObjectResult("Azure Maps Subscription Key is missing.");
37+
}
3138

32-
// Get the geolocation from Azure Maps
33-
var result = await _HttpClient.GetFromJsonAsync<Geolocation>(url);
34-
if (result == null)
35-
{
36-
return new BadRequestObjectResult("An error occurred. It was not possible to get the location of this IP address.");
39+
string url = $"https://atlas.microsoft.com/geolocation/ip/json?subscription-key={azureMapsKey}&api-version=1.0&ip={ip}";
40+
Geolocation result = await GetGeolocationFromAzureMaps(url);
41+
42+
if (result?.CountryRegion?.IsoCode == null)
43+
{
44+
return new BadRequestObjectResult("An error occurred. It was not possible to get the location of this IP address.");
45+
}
46+
47+
RegionInfo region = new(result.CountryRegion.IsoCode);
48+
string json = JsonSerializer.Serialize(region);
49+
50+
return new OkObjectResult(json);
3751
}
3852

39-
// Get the region from the geolocation
40-
var region = new RegionInfo(result.CountryRegion.IsoCode);
41-
var json = JsonSerializer.Serialize(region);
53+
// Retrun access denied if the referer domain is not allowed
54+
return new StatusCodeResult(StatusCodes.Status403Forbidden);
55+
}
4256

43-
return new OkObjectResult(json);
57+
private static async Task<Geolocation> GetGeolocationFromAzureMaps(string url)
58+
{
59+
try
60+
{
61+
return await HttpClient.GetFromJsonAsync<Geolocation>(url);
62+
}
63+
catch
64+
{
65+
return null;
66+
}
4467
}
4568
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
using Microsoft.AspNetCore.Http;
2+
using Microsoft.AspNetCore.Mvc;
3+
using Microsoft.Azure.Functions.Worker;
4+
5+
namespace SampleFunctions;
6+
7+
public class GetMIOKey
8+
{
9+
private static readonly string[] AllowedDomains = [
10+
"https://samples.azuremaps.com/",
11+
"https://www.microsoft.com/",
12+
"http://localhost:58745/" // For local testing
13+
];
14+
15+
[Function("GetMIOKey")]
16+
public static IActionResult Run(
17+
[HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req)
18+
{
19+
// Check if the referer header is present and if the domain is allowed
20+
if (req.Headers.TryGetValue("Referer", out var referer) && AllowedDomains.Any(domain => referer.ToString().StartsWith(domain)))
21+
{
22+
// Get your NVIDIA cuOpt key from https://developer.nvidia.com/
23+
var key = Environment.GetEnvironmentVariable("NVIDIA_SUBSCRIPTION_KEY");
24+
25+
return new OkObjectResult(key);
26+
}
27+
28+
// Retrun access denied if the referer domain is not allowed
29+
return new StatusCodeResult(StatusCodes.Status403Forbidden);
30+
}
31+
}

‎Services/SampleFunctions/SampleFunctions.csproj‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.1.0" />
1414
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="1.2.1" />
1515
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.17.2" />
16-
<PackageReference Include="Azure.Identity" Version="1.11.2" />
16+
<PackageReference Include="Azure.Identity" Version="1.11.3" />
1717
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" />
1818
<PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="1.2.0" />
1919
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="8.0.0" />

0 commit comments

Comments
 (0)