AspNetCore.Docs/aspnetcore/security/enforcing-ssl.md

41 lines
2.0 KiB
Markdown
Raw Normal View History

2016-10-29 01:35:15 +08:00
---
title: Enforcing HTTPS in an ASP.NET Core app
2016-10-29 01:35:15 +08:00
author: rick-anderson
description: Shows how to require HTTPS/TLS in a ASP.NET Core web app.
2016-10-29 01:35:15 +08:00
manager: wpickett
2018-01-29 23:21:31 +08:00
ms.author: riande
ms.date: 2/9/2018
ms.prod: asp.net-core
2018-01-29 23:21:31 +08:00
ms.technology: aspnet
ms.topic: article
2016-10-29 01:35:15 +08:00
uid: security/enforcing-ssl
---
# Enforcing HTTPS in an ASP.NET Core app
2016-10-29 01:35:15 +08:00
2017-07-19 06:01:43 +08:00
By [Rick Anderson](https://twitter.com/RickAndMSFT)
This document shows how to:
- Require HTTPS for all requests.
- Redirect all HTTP requests to HTTPS.
> [!WARNING]
> Do **not** use `RequireHttpsAttribute` on Web APIs that receive sensitive information. `RequireHttpsAttribute` uses HTTP status codes to redirect browsers from HTTP to HTTPS. API clients may not understand or obey redirects from HTTP to HTTPS. Such clients may send information over HTTP. Web APIs should either:
>
>* Not listen on HTTP.
>* Close the connection with status code 400 (Bad Request) and not serve the request.
## Require HTTPS
The [RequireHttpsAttribute](/dotnet/api/Microsoft.AspNetCore.Mvc.RequireHttpsAttribute) is used to require HTTPS. `[RequireHttpsAttribute]` can decorate controllers or methods, or can be applied globally. To apply the attribute globally, add the following code to `ConfigureServices` in `Startup`:
2018-02-03 03:16:49 +08:00
[!code-csharp[Main](authentication/accconfirm/sample/WebApp1/Startup.cs?name=snippet2&highlight=4-999)]
The preceding highlighted code requires all requests use `HTTPS`; therefore, HTTP requests are ignored. The following highlighted code redirects all HTTP requests to HTTPS:
2018-02-03 03:16:49 +08:00
[!code-csharp[Main](authentication/accconfirm/sample/WebApp1/Startup.cs?name=snippet_AddRedirectToHttps&highlight=7-999)]
For more information, see [URL Rewriting Middleware](xref:fundamentals/url-rewriting).
Requiring HTTPS globally (`options.Filters.Add(new RequireHttpsAttribute());`) is a security best practice. Applying the
`[RequireHttps]` attribute to all controllers/Razor Pages isn't considered as secure as requiring HTTPS globally. You can't guarantee the `[RequireHttps]` attribute is applied when new controllers and Razor Pages are added.