FluffySpoon.AspNet.EncryptWeMust.EntityFramework
1.240.0
Prefix Reserved
dotnet add package FluffySpoon.AspNet.EncryptWeMust.EntityFramework --version 1.240.0
NuGet\Install-Package FluffySpoon.AspNet.EncryptWeMust.EntityFramework -Version 1.240.0
<PackageReference Include="FluffySpoon.AspNet.EncryptWeMust.EntityFramework" Version="1.240.0" />
paket add FluffySpoon.AspNet.EncryptWeMust.EntityFramework --version 1.240.0
#r "nuget: FluffySpoon.AspNet.EncryptWeMust.EntityFramework, 1.240.0"
// Install FluffySpoon.AspNet.EncryptWeMust.EntityFramework as a Cake Addin #addin nuget:?package=FluffySpoon.AspNet.EncryptWeMust.EntityFramework&version=1.240.0 // Install FluffySpoon.AspNet.EncryptWeMust.EntityFramework as a Cake Tool #tool nuget:?package=FluffySpoon.AspNet.EncryptWeMust.EntityFramework&version=1.240.0
What is this?
The simplest LetsEncrypt setup for ASP .NET Core. Almost no server configuration needed.
Install-Package FluffySpoon.AspNet.EncryptWeMust
This project used to be called FluffySpoon.AspNet.LetsEncrypt
, but due to a trademark claim from LetsEncrypt, we had to rename it. The name now follows Yoda Speak.
Requirements
- Kestrel (which is default)
- ASP .NET Core 2.1+
- An always-on app-pool
Getting an always-on app pool
This is required because the renewal job runs on a background thread and polls once every hour to see if the certificate needs renewal (this is a very cheap operation).
It can be enabled using just one the following techniques:
- Enabling Always On if using Azure App Service.
- Setting
StartMode
of the app pool toAlwaysRunning
if using IIS. - Hosting your ASP .NET Core application as a Windows Service.
Usage example
If you want to try it yourself, you can also browse the sample project code here:
Configure the services
Add the following code to your Startup
class' ConfigureServices
method with real values instead of the sample values:
Note that you can set either TimeUntilExpiryBeforeRenewal
, TimeAfterIssueDateBeforeRenewal
or both, but at least one of them has to be specified.
//the following line adds the automatic renewal service.
services.AddFluffySpoonLetsEncrypt(new LetsEncryptOptions()
{
Email = "some-email@github.com", //LetsEncrypt will send you an e-mail here when the certificate is about to expire
UseStaging = false, //switch to true for testing
Domains = new[] { DomainToUse },
TimeUntilExpiryBeforeRenewal = TimeSpan.FromDays(30), //renew automatically 30 days before expiry
TimeAfterIssueDateBeforeRenewal = TimeSpan.FromDays(7), //renew automatically 7 days after the last certificate was issued
CertificateSigningRequest = new CsrInfo() //these are your certificate details
{
CountryName = "Denmark",
Locality = "DK",
Organization = "Fluffy Spoon",
OrganizationUnit = "Hat department",
State = "DK"
}
});
//the following line tells the library to persist the certificate to a file, so that if the server restarts, the certificate can be re-used without generating a new one.
services.AddFluffySpoonLetsEncryptFileCertificatePersistence();
//the following line tells the library to persist challenges in-memory. challenges are the "/.well-known" URL codes that LetsEncrypt will call.
services.AddFluffySpoonLetsEncryptMemoryChallengePersistence();
Inject the middleware
Inject the middleware in the Startup
class' Configure
method as such:
public void Configure()
{
app.UseFluffySpoonLetsEncrypt();
}
Set default bindings
Call UseUrls with http://* and https://* in Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseUrls(new string[] { "http://*", "https://*" });
webBuilder.UseStartup<Startup>();
});
Tada! Your application now supports SSL via LetsEncrypt, even from the first HTTPS request. It will even renew your certificate automatically in the background.
Optional: Configuring persistence
Persistence tells the middleware how to persist and retrieve the certificate, so that if the server restarts, the certificate can be re-used without generating a new one.
A certificate has a key to distinguish between certificates, since there is both an account certificate and a site certificate that needs to be stored.
File persistence
services.AddFluffySpoonLetsEncryptFileCertificatePersistence();
services.AddFluffySpoonLetsEncryptFileChallengePersistence();
Custom persistence
services.AddFluffySpoonLetsEncryptCertificatePersistence(/* your own ILetsEncryptPersistence implementation */);
services.AddFluffySpoonLetsEncryptChallengePersistence(/* your own ILetsEncryptPersistence implementation */);
//you can also customize persistence via delegates.
services.AddFluffySpoonLetsEncryptCertificatePersistence(
async (key, bytes) => File.WriteAllBytes("certificate_" + key, bytes),
async (key) => File.ReadAllBytes("certificate_" + key, bytes));
//the same can be done for challenges, with different arguments.
services.AddFluffySpoonLetsEncryptChallengePersistence(
async (challenges) => ... /* Do something to serialize the collection of challenges and store it */,
async () => ... /* Retrieve the stored collection of challenges */,
async (challenges) => ... /* Delete the specified challenges */);
Entity Framework persistence
Requires the NuGet package FluffySpoon.AspNet.EncryptWeMust.EntityFramework
.
// Certificate and Challenge in this example are database model classes that have been configured with the database context.
class Certificate {
[Key]
public string Key { get; set; }
public byte[] Bytes { get; set; }
}
public class Challenge
{
[Key]
public string Token { get; set; }
public string Response { get; set; }
public int Type { get; set; }
public string Domains { get; set; }
}
//we only have to instruct how to add the certificate - `databaseContext.SaveChangesAsync()` is automatically called.
services.AddFluffySpoonLetsEncryptEntityFrameworkCertificatePersistence<DatabaseContext>(
async (databaseContext, key, bytes) =>
{
var existingCertificate = databaseContext.Certificates.SingleOrDefault(x => x.Key == key);
if (existingCertificate != null)
{
existingCertificate.Bytes = bytes;
}
else
{
databaseContext.Certificates.Add(new Certificate()
{
Key = key,
Bytes = bytes
});
}
},
async (databaseContext, key) => databaseContext
.Certificates
.SingleOrDefault(x => x.Key == key)
?.Bytes);
//the same can be done for challenges
services.AddFluffySpoonLetsEncryptEntityFrameworkChallengePersistence<DatabaseContext>(
async (databaseContext, challenges) => databaseContext
.Challenges
.AddRange(
challenges.Select(x =>
new Challenge()
{
Token = x.Token,
Response = x.Response,
Type = (int)x.Type,
Domains = String.Join(",", x.Domains)
})),
async (databaseContext) => databaseContext
.Challenges
.Select(x =>
new ChallengeDto()
{
Token = x.Token,
Response = x.Response,
Type = (ChallengeType)x.Type,
Domains = x.Domains.Split(',', StringSplitOptions.RemoveEmptyEntries)
}),
async (databaseContext, challenges) => databaseContext
.Challenges
.RemoveRange(
databaseContext
.Challenges
.Where(x => challenges.Any(y => y.Token == x.Token))
));
Distributed cache (Redis etc) persistence
Requires:
- The NuGet package
FluffySpoon.AspNet.EncryptWeMust.DistributedCache
. - A configured distributed cache in ASP .NET Core using the
services.AddDistributedRedisCache()
or similar.
services.AddFluffySpoonLetsEncryptDistributedCertificatePersistence(expiry: TimeSpan.FromDays(30));
services.AddFluffySpoonLetsEncryptDistributedChallengePersistence(expiry: TimeSpan.FromHours(1));
Azure App Service
Using this project when running as an Azure App Service requires a few things.
Firstly the App Service Plan needs to have the "Custom domains / SSL" feature (currently B1 for testing, S1 for production are the lowest supported).
Secondly you should use the AzureAppServiceSslBindingCertificatePersistenceStrategy
strategy:
services.AddFluffySpoonLetsEncryptAzureAppServiceSslBindingCertificatePersistence(
new AzureOptions {
ResourceGroupName = ..., // The resource group the App Service is deployed to
Credentials = ... // Get some credentials that have access to Azure
});
The credentials supplied above need to have access to create certificates and set SSL bindings for the App Service. The permissions to create certificates is for the resource group and they are created as resources in the group, not in the App Service itself. The SSL bindings are set on the App Service. Bottom line is that you can achieve this by granting the Website Contributor to whatever principal you wish to use (the credentials in the snippet above).
The easiest way to get some usable credentials is to use a System Assigned Managed Identity. This can be enabled on an App Service as described here.
Having done that the following snippet sets this up:
var managedIdentityCredentials = new AzureCredentialsFactory()
.FromMSI(
new MSILoginInformation(MSIResourceType.AppService),
AzureEnvironment.AzureGlobalCloud);
services.AddFluffySpoonLetsEncryptAzureAppServiceSslBindingCertificatePersistence(
new AzureOptions {
ResourceGroupName = System.Environment.GetEnvironmentVariable("WEBSITE_RESOURCE_GROUP"),
Credentials = managedIdentityCredentials
});
The resource group for the App Service can also easily be accessed through an environment variable, as specified above.
Hooking into events
You can register a an ICertificateRenewalLifecycleHook
implementation which does something when certain events occur, as shown below. This can be useful if you need to notify a Slack channel or send an e-mail if an error occurs, or when the certificate has indeed been renewed.
class MyLifecycleHook : ICertificateRenewalLifecycleHook {
public async Task OnStartAsync() {
//when the renewal background job has started.
}
public async Task OnStopAsync() {
//when the renewal background job (or the application) has stopped.
//this is not guaranteed to fire in critical application crash scenarios.
}
public async Task OnRenewalSucceededAsync() {
//when the renewal has completed.
}
public async Task OnExceptionAsync(Exception error) {
//when an error happened during the renewal process.
}
}
//this is how to wire up the hook.
services.AddFluffySpoonLetsEncryptRenewalLifecycleHook<MyLifecycleHook>();
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
-
net6.0
- FluffySpoon.AspNet.EncryptWeMust (>= 1.0.0)
- Microsoft.EntityFrameworkCore (>= 6.0.4)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 6.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last updated |
---|---|---|
1.240.0 | 213 | 3/11/2024 |
1.239.0 | 928 | 5/2/2022 |
1.216.0 | 1,244 | 4/7/2021 |
1.212.0 | 498 | 4/2/2021 |
1.211.0 | 779 | 3/17/2021 |
1.209.0 | 423 | 3/16/2021 |
1.207.0 | 428 | 3/15/2021 |
1.205.0 | 541 | 3/10/2021 |
1.201.0 | 582 | 3/2/2021 |
1.199.0 | 599 | 2/24/2021 |
1.198.0 | 733 | 2/10/2021 |
1.194.0 | 492 | 2/5/2021 |
1.192.0 | 975 | 1/14/2021 |
1.191.0 | 436 | 1/13/2021 |
1.188.0 | 616 | 1/7/2021 |
1.187.0 | 456 | 1/6/2021 |
1.171.0 | 4,465 | 7/26/2020 |
1.169.0 | 1,696 | 6/5/2020 |
1.168.0 | 539 | 6/5/2020 |
1.167.0 | 637 | 6/1/2020 |