forked from blowdart/idunno.Authentication
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCertificateForwarderMiddleware.cs
73 lines (61 loc) · 2.37 KB
/
CertificateForwarderMiddleware.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
65
66
67
68
69
70
71
72
73
// Copyright (c) Barry Dorrans. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace idunno.Authentication.Certificate
{
public class CertificateForwarderMiddleware
{
private readonly RequestDelegate _next;
private readonly CertificateForwarderOptions _options;
private readonly ILogger _logger;
public CertificateForwarderMiddleware(
RequestDelegate next,
ILoggerFactory loggerFactory,
IOptions<CertificateForwarderOptions> options)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_options = options.Value;
_logger = loggerFactory.CreateLogger<CertificateForwarderMiddleware>();
}
public async Task Invoke(HttpContext httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
if (!string.IsNullOrWhiteSpace(_options.CertificateHeader))
{
var clientCertificate = await httpContext.Connection.GetClientCertificateAsync();
if (clientCertificate == null)
{
// Check for forwarding header
string certificateHeader = httpContext.Request.Headers[_options.CertificateHeader];
if (!string.IsNullOrEmpty(certificateHeader))
{
try
{
httpContext.Connection.ClientCertificate = _options.HeaderConverter(certificateHeader);
}
catch
{
_logger.LogError("Could not read certificate from header.");
}
}
}
}
await _next(httpContext);
}
}
}