|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using Microsoft.AspNetCore.Http; |
| 7 | +using Microsoft.AspNetCore.Http.Features; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | +using Microsoft.Extensions.Options; |
| 10 | +using Microsoft.Extensions.Primitives; |
| 11 | + |
| 12 | +namespace Microsoft.AspNetCore.HttpOverrides |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Middleware that converts a forward header into a client certificate if found. |
| 16 | + /// </summary> |
| 17 | + public class CertificateForwardingMiddleware |
| 18 | + { |
| 19 | + private readonly RequestDelegate _next; |
| 20 | + private readonly CertificateForwardingOptions _options; |
| 21 | + private readonly ILogger _logger; |
| 22 | + |
| 23 | + /// <summary> |
| 24 | + /// Constructor. |
| 25 | + /// </summary> |
| 26 | + /// <param name="next"></param> |
| 27 | + /// <param name="loggerFactory"></param> |
| 28 | + /// <param name="options"></param> |
| 29 | + public CertificateForwardingMiddleware( |
| 30 | + RequestDelegate next, |
| 31 | + ILoggerFactory loggerFactory, |
| 32 | + IOptions<CertificateForwardingOptions> options) |
| 33 | + { |
| 34 | + _next = next ?? throw new ArgumentNullException(nameof(next)); |
| 35 | + |
| 36 | + if (loggerFactory == null) |
| 37 | + { |
| 38 | + throw new ArgumentNullException(nameof(loggerFactory)); |
| 39 | + } |
| 40 | + |
| 41 | + if (options == null) |
| 42 | + { |
| 43 | + throw new ArgumentNullException(nameof(options)); |
| 44 | + } |
| 45 | + |
| 46 | + _options = options.Value; |
| 47 | + _logger = loggerFactory.CreateLogger<CertificateForwardingMiddleware>(); |
| 48 | + } |
| 49 | + |
| 50 | + /// <summary> |
| 51 | + /// Looks for the presence of a <see cref="CertificateForwardingOptions.CertificateHeader"/> header in the request, |
| 52 | + /// if found, converts this header to a ClientCertificate set on the connection. |
| 53 | + /// </summary> |
| 54 | + /// <param name="httpContext">The <see cref="HttpContext"/>.</param> |
| 55 | + /// <returns>A <see cref="Task"/>.</returns> |
| 56 | + public Task Invoke(HttpContext httpContext) |
| 57 | + { |
| 58 | + var header = httpContext.Request.Headers[_options.CertificateHeader]; |
| 59 | + if (!StringValues.IsNullOrEmpty(header)) |
| 60 | + { |
| 61 | + httpContext.Features.Set<ITlsConnectionFeature>(new CertificateForwardingFeature(_logger, header, _options)); |
| 62 | + } |
| 63 | + return _next(httpContext); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments