forked from juunas11/aspnetcore-security-headers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFeaturePolicyMiddleware.cs
43 lines (37 loc) · 1.37 KB
/
FeaturePolicyMiddleware.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
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
namespace Joonasw.AspNetCore.SecurityHeaders.FeaturePolicy
{
public class FeaturePolicyMiddleware
{
private const string HeaderName = "Permissions-Policy";
private readonly RequestDelegate _next;
private readonly string _headerValue;
public FeaturePolicyMiddleware(RequestDelegate next, IOptions<FeaturePolicyOptions> options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_next = next;
_headerValue = options.Value.ToString();
}
public async Task Invoke(HttpContext context)
{
// Check if a Feature Policy header has already been added to the response
// This can happen for example if a middleware re-executes the pipeline
if (!ContainsFeaturePolicyHeader(context.Response))
{
context.Response.Headers.Add(HeaderName, _headerValue);
}
await _next.Invoke(context);
}
private static bool ContainsFeaturePolicyHeader(HttpResponse response)
{
return response.Headers.Any(h => h.Key.Equals(HeaderName, StringComparison.OrdinalIgnoreCase));
}
}
}