This repository has been archived by the owner on Dec 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 84
Adds Https Redirection and Hsts Middlewares #264
Merged
Merged
Changes from 11 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
d9f364d
Adds HttpEnforcement and Hsts Middleware
jkotalik 18d6c96
most of the feedback. TODO clean up httpsPolicyBuilder and ServiceCol…
jkotalik 9d3c8b2
trying to fix DI issues
jkotalik 4d27202
Redesign of middleware incoming
jkotalik 4a9495e
feedback
jkotalik e9a1f5a
Feedback, TODO default for Hsts
jkotalik 82401ac
Visual studio version
jkotalik e38ac6e
Revert sln changes
jkotalik 8c11086
Offline feedback and discussion
jkotalik a588a98
Comments!
jkotalik 3aa120c
Feedback!
jkotalik f72cb24
modify samples
jkotalik a704d29
super small nit
jkotalik 23412eb
Feedback
jkotalik File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<TargetFrameworks>net461;netcoreapp2.0</TargetFrameworks> | ||
<TargetFrameworks Condition=" '$(OS)' != 'Windows_NT' ">netcoreapp2.0</TargetFrameworks> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" /> | ||
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Https" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\..\src\Microsoft.AspNetCore.HttpsPolicy\Microsoft.AspNetCore.HttpsPolicy.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
{ | ||
"iisSettings": { | ||
"windowsAuthentication": false, | ||
"anonymousAuthentication": true, | ||
"iisExpress": { | ||
"applicationUrl": "http://localhost:31894/", | ||
"sslPort": 0 | ||
} | ||
}, | ||
"profiles": { | ||
"IIS Express": { | ||
"commandName": "IISExpress", | ||
"launchBrowser": true, | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
} | ||
}, | ||
"HttpsSample": { | ||
"commandName": "Project", | ||
"launchBrowser": true, | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
}, | ||
"applicationUrl": "http://localhost:31895/" | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Net; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Builder; | ||
using Microsoft.AspNetCore.Hosting; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.AspNetCore.HttpsPolicy; | ||
using Microsoft.Extensions.DependencyInjection; | ||
|
||
namespace HttpsSample | ||
{ | ||
public class Startup | ||
{ | ||
// This method gets called by the runtime. Use this method to add services to the container. | ||
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 | ||
public void ConfigureServices(IServiceCollection services) | ||
{ | ||
services.Configure<HttpsRedirectionOptions>(options => { | ||
options.RedirectStatusCode = StatusCodes.Status301MovedPermanently; | ||
options.TlsPort = 5001; | ||
}); | ||
|
||
services.Configure<HstsOptions>(options => | ||
{ | ||
options.MaxAge = TimeSpan.FromSeconds(5000); | ||
options.Preload = true; | ||
options.IncludeSubDomains = true; | ||
}); | ||
} | ||
|
||
public void Configure(IApplicationBuilder app, IHostingEnvironment environment) | ||
{ | ||
if (!environment.IsDevelopment()) | ||
{ | ||
app.UseHsts(); | ||
} | ||
app.UseHttpsRedirection(); | ||
|
||
app.Run(async context => | ||
{ | ||
await context.Response.WriteAsync("Hello world!"); | ||
}); | ||
} | ||
|
||
// Entry point for the application. | ||
public static void Main(string[] args) | ||
{ | ||
var host = new WebHostBuilder() | ||
.UseKestrel( | ||
options => | ||
{ | ||
options.Listen(new IPEndPoint(IPAddress.Loopback, 5001), listenOptions => | ||
{ | ||
listenOptions.UseHttps("testCert.pfx", "testPassword"); | ||
}); | ||
options.Listen(new IPEndPoint(IPAddress.Loopback, 5000), listenOptions => | ||
{ | ||
}); | ||
}) | ||
.UseContentRoot(Directory.GetCurrentDirectory()) // for the cert file | ||
.UseStartup<Startup>() | ||
.Build(); | ||
|
||
host.Run(); | ||
} | ||
} | ||
} |
Binary file not shown.
30 changes: 30 additions & 0 deletions
30
src/Microsoft.AspNetCore.HttpsPolicy/HstsBuilderExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using System; | ||
using Microsoft.AspNetCore.Builder; | ||
using Microsoft.AspNetCore.HttpsPolicy; | ||
using Microsoft.Extensions.Options; | ||
|
||
namespace Microsoft.AspNetCore.Builder | ||
{ | ||
/// <summary> | ||
/// Extension methods for the HSTS middleware. | ||
/// </summary> | ||
public static class HstsBuilderExtensions | ||
{ | ||
/// <summary> | ||
/// Adds middleware for using HSTS, which adds the Strict-Transport-Security header. | ||
/// </summary> | ||
/// <param name="app">The <see cref="IApplicationBuilder"/> instance this method extends.</param> | ||
public static IApplicationBuilder UseHsts(this IApplicationBuilder app) | ||
{ | ||
if (app == null) | ||
{ | ||
throw new ArgumentNullException(nameof(app)); | ||
} | ||
|
||
return app.UseMiddleware<HstsMiddleware>(); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
// Copyright (c) .NET Foundation. 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.Options; | ||
using Microsoft.Extensions.Primitives; | ||
using Microsoft.Net.Http.Headers; | ||
|
||
namespace Microsoft.AspNetCore.HttpsPolicy | ||
{ | ||
/// <summary> | ||
/// Enables HTTP Strict Transport Security (HSTS) | ||
/// See https://tools.ietf.org/html/rfc6797. | ||
/// </summary> | ||
public class HstsMiddleware | ||
{ | ||
private const string IncludeSubDomains = "; includeSubDomains"; | ||
private const string Preload = "; preload"; | ||
|
||
private readonly RequestDelegate _next; | ||
private readonly StringValues _strictTransportSecurityValue; | ||
|
||
/// <summary> | ||
/// Initialize the HSTS middleware. | ||
/// </summary> | ||
/// <param name="next"></param> | ||
/// <param name="options"></param> | ||
public HstsMiddleware(RequestDelegate next, IOptions<HstsOptions> options) | ||
{ | ||
if (next == null) | ||
{ | ||
throw new ArgumentNullException(nameof(next)); | ||
} | ||
|
||
if (options == null) | ||
{ | ||
throw new ArgumentNullException(nameof(options)); | ||
} | ||
|
||
_next = next; | ||
|
||
var hstsOptions = options.Value; | ||
var includeSubdomains = hstsOptions.IncludeSubDomains ? IncludeSubDomains : StringSegment.Empty; | ||
var preload = hstsOptions.Preload ? Preload : StringSegment.Empty; | ||
|
||
_strictTransportSecurityValue = new StringValues($"max-age={hstsOptions.MaxAge.TotalSeconds}{includeSubdomains}{preload}"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nvrm realized I realized that security has max age as nullable. |
||
} | ||
|
||
/// <summary> | ||
/// Invoke the middleware. | ||
/// </summary> | ||
/// <param name="context">The <see cref="HttpContext"/>.</param> | ||
/// <returns></returns> | ||
public Task Invoke(HttpContext context) | ||
{ | ||
if (context.Request.IsHttps) | ||
{ | ||
context.Response.Headers[HeaderNames.StrictTransportSecurity] = _strictTransportSecurityValue; | ||
} | ||
|
||
return _next(context); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should have a blank line before the return statement. |
||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using System; | ||
|
||
namespace Microsoft.AspNetCore.HttpsPolicy | ||
{ | ||
/// <summary> | ||
/// Options for the Hsts Middleware | ||
/// </summary> | ||
public class HstsOptions | ||
{ | ||
/// <summary> | ||
/// Sets the max-age parameter of the Strict-Transport-Security header. | ||
/// </summary> | ||
/// <remarks> | ||
/// Max-age is required; defaults to 30 days. | ||
/// See: https://tools.ietf.org/html/rfc6797#section-6.1.1 | ||
/// </remarks> | ||
public TimeSpan MaxAge { get; set; } = TimeSpan.FromDays(30); | ||
|
||
/// <summary> | ||
/// Enables includeSubDomain parameter of the Strict-Transport-Security header. | ||
/// </summary> | ||
/// <remarks> | ||
/// See: https://tools.ietf.org/html/rfc6797#section-6.1.2 | ||
/// </remarks> | ||
public bool IncludeSubDomains { get; set; } | ||
|
||
/// <summary> | ||
/// Sets the preload parameter of the Strict-Transport-Security header. | ||
/// </summary> | ||
/// <remarks> | ||
/// Preload is not part of the RFC specification, but is supported by web browsers | ||
/// to preload HSTS sites on fresh install. See https://hstspreload.org/. | ||
/// </remarks> | ||
public bool Preload { get; set; } | ||
} | ||
} |
36 changes: 36 additions & 0 deletions
36
src/Microsoft.AspNetCore.HttpsPolicy/HstsServicesExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using System; | ||
using Microsoft.AspNetCore.HttpsPolicy; | ||
using Microsoft.Extensions.DependencyInjection; | ||
|
||
namespace Microsoft.AspNetCore.Builder | ||
{ | ||
/// <summary> | ||
/// Extension methods for the HSTS middleware. | ||
/// </summary> | ||
public static class HstsServicesExtensions | ||
{ | ||
/// <summary> | ||
/// Adds HSTS services. | ||
/// </summary> | ||
/// <param name="services">The <see cref="IServiceCollection"/> for adding services.</param> | ||
/// <param name="configureOptions">A delegate to configure the <see cref="HstsOptions"/>.</param> | ||
/// <returns></returns> | ||
public static IServiceCollection AddHsts(this IServiceCollection services, Action<HstsOptions> configureOptions) | ||
{ | ||
if (services == null) | ||
{ | ||
throw new ArgumentNullException(nameof(services)); | ||
} | ||
if (configureOptions == null) | ||
{ | ||
throw new ArgumentNullException(nameof(configureOptions)); | ||
} | ||
|
||
services.Configure(configureOptions); | ||
return services; | ||
} | ||
} | ||
} |
44 changes: 44 additions & 0 deletions
44
src/Microsoft.AspNetCore.HttpsPolicy/HttpsRedirectionBuilderExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using System; | ||
using Microsoft.AspNetCore.HttpsPolicy; | ||
using Microsoft.AspNetCore.Rewrite; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Options; | ||
|
||
namespace Microsoft.AspNetCore.Builder | ||
{ | ||
/// <summary> | ||
/// Extension methods for the HttpsRedirection middleware. | ||
/// </summary> | ||
public static class HttpsPolicyBuilderExtensions | ||
{ | ||
/// <summary> | ||
/// Adds middleware for redirecting HTTP Requests to HTTPS. | ||
/// </summary> | ||
/// <param name="app">The <see cref="IApplicationBuilder"/> instance this method extends.</param> | ||
/// <returns>The <see cref="IApplicationBuilder"/> for HttpsRedirection.</returns> | ||
/// <remarks> | ||
/// HTTPS Enforcement interanlly uses the UrlRewrite middleware to redirect HTTP requests to HTTPS. | ||
/// </remarks> | ||
public static IApplicationBuilder UseHttpsRedirection(this IApplicationBuilder app) | ||
{ | ||
if (app == null) | ||
{ | ||
throw new ArgumentNullException(nameof(app)); | ||
} | ||
|
||
var options = app.ApplicationServices.GetRequiredService<IOptions<HttpsRedirectionOptions>>().Value; | ||
|
||
var rewriteOptions = new RewriteOptions(); | ||
rewriteOptions.AddRedirectToHttps( | ||
options.RedirectStatusCode, | ||
options.TlsPort); | ||
|
||
app.UseRewriter(rewriteOptions); | ||
|
||
return app; | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Update the samples to use the helper methods