This is a Cosmos DB implementation of an Identity provider for .NET 8 that uses the "EF Core Azure Cosmos DB Provider".
When upgrading to version 8 from 2, you will need to make two changes to your project:
The old way of creating the Database Context looked like this:
public class ApplicationDbContext : CosmosIdentityDbContext<IdentityUser, IdentityRole>
The new way is like this (with 'string' added):
public class ApplicationDbContext : CosmosIdentityDbContext<IdentityUser, IdentityRole, string>
Next, in your Program.cs or Startup.cs files, change from this:
builder.Services.AddCosmosIdentity<ApplicationDbContext, IdentityUser, IdentityRole>
To this (with 'string' added):
builder.Services.AddCosmosIdentity<ApplicationDbContext, IdentityUser, IdentityRole, string>
Tip: This package uses seven (7) "containers." If the RU throughput for your Cosmos Account is configured at the "container" level, this can require your Cosmos DB Account to require a higher minimum RU.
To keep costs down, consider sharing throughput at the database level as described here in the documentation. This allows you to, for example, set the RU at the database to be 1,000 RU, then have all containers within that database share those RU's.
Next, set the RU to "autoscale." According to documentation, "Autoscale provisioned throughput in Azure Cosmos DB allows you to scale the throughput (RU/s) of your database or container automatically and instantly." This will allow your database to scale down and up as needed, thus reducing your monthly costs further.
Add the following NuGet package to your project:
PM> Install-Package AspNetCore.Identity.CosmosDb
Create an Azure Cosmos DB account - either the free, serverless or dedicated instance. For testing and development purposes it is recommended to use a free account. See documentation to help choose which type of Cosmos account is best for you.
Set your configuration settings with the connection string and database name. Below is an example of a secrets.json
file:
{
"SetupCosmosDb": "true", // Importat: Remove this after first run.
"CosmosIdentityDbName": "YourDabatabaseName",
"ConnectionStrings": {
"ApplicationDbContextConnection": "THE CONNECTION STRING TO YOUR COSMOS ACCOUNT"
}
}
Modify the database context to inherit from the CosmosIdentityDbContext
like this:
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace AspNetCore.Identity.CosmosDb.Example.Data
{
public class ApplicationDbContext : CosmosIdentityDbContext<IdentityUser, IdentityRole, string>
{
public ApplicationDbContext(DbContextOptions dbContextOptions)
: base(dbContextOptions) { }
}
}
After the "secrets" have been set, the next task is to modify your project's startup file. For Asp.net
6 and higher that might be the Project.cs
file. For other projects it might be your Startup.cs.
You will likely need to add these usings:
using AspNetCore.Identity.CosmosDb;
using AspNetCore.Identity.CosmosDb.Containers;
using AspNetCore.Identity.CosmosDb.Extensions;
Next, the configuration variables need to be retrieved. Add the following to your startup file:
// The Cosmos connection string
var connectionString = builder.Configuration.GetConnectionString("ApplicationDbContextConnection");
// Name of the Cosmos database to use
var cosmosIdentityDbName = builder.Configuration.GetValue<string>("CosmosIdentityDbName");
// If this is set, the Cosmos identity provider will:
// 1. Create the database if it does not already exist.
// 2. Create the required containers if they do not already exist.
// IMPORTANT: Remove this setting if after first run. It will improve startup performance.
var setupCosmosDb = builder.Configuration.GetValue<string>("SetupCosmosDb");
Add this code if you want the provider to create the database and required containers:
// If the following is set, it will create the Cosmos database and
// required containers.
if (bool.TryParse(setupCosmosDb, out var setup) && setup)
{
var builder1 = new DbContextOptionsBuilder<ApplicationDbContext>();
builder1.UseCosmos(connectionString, cosmosIdentityDbName);
using (var dbContext = new ApplicationDbContext(builder1.Options))
{
dbContext.Database.EnsureCreated();
}
}
Now add the database context in your startup file like this:
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseCosmos(connectionString: connectionString, databaseName: cosmosIdentityDbName));
Follow that up with the identity provider. Here is an example:
builder.Services.AddCosmosIdentity<ApplicationDbContext, IdentityUser, IdentityRole, string>(
options => options.SignIn.RequireConfirmedAccount = true // Always a good idea :)
)
.AddDefaultUI() // Use this if Identity Scaffolding is in use
.AddDefaultTokenProviders();
This library works with external OAuth providers, and below is an example of how we implement this.
Begin by adding these two NuGet packages to your project:
Then add the code below to your Project.cs file.
// Example of adding OAuth Providers
// Add Google if keys are present
var googleClientId = Configuration["Authentication_Google_ClientId"];
var googleClientSecret = Configuration["Authentication_Google_ClientSecret"];
// If Google ID and secret are both found, then add the provider.
if (!string.IsNullOrEmpty(googleClientId) && !string.IsNullOrEmpty(googleClientSecret))
{
builder.Services.AddAuthentication().AddGoogle(options =>
{
options.ClientId = googleClientId;
options.ClientSecret = googleClientSecret;
});
}
// Add Microsoft if keys are present
var microsoftClientId = Configuration["Authentication_Microsoft_ClientId"];
var microsoftClientSecret = Configuration["Authentication_Microsoft_ClientSecret"];
// If Microsoft ID and secret are both found, then add the provider.
if (!string.IsNullOrEmpty(microsoftClientId) && !string.IsNullOrEmpty(microsoftClientSecret))
{
builder.Services.AddAuthentication().AddMicrosoftAccount(options =>
{
options.ClientId = microsoftClientId;
options.ClientSecret = microsoftClientSecret;
});
}
To learn more about external OAuth providers, please see the Microsoft documentation on this subject.
The above instructions showed how to modify the startup file to make use of this provider. Sometimes it is easier to see the end result rather than peicemeal. Here is an example Asp.Net 6 Project.cs file configured to work with this provider, scaffolded identity web pages, and the SendGrid email provider:
An example website is available for you to download and try.
Both the user and role stores now support queries via LINQ using Entity Framework. Here is an example:
var userResults = userManager.Users.Where(u => u.Email.StartsWith("bob"));
var roleResults = roleManager.Roles.Where (r => r.Name.Contains("water"));
For a list of supported LINQ operations, please see the "Supported LINQ Operations" documentation for more details.
Find a bug? Let us know by contacting us via NuGet or submit a bug report on our GitHub issues section. Thank you in advance!
This change log notes major changes beyond routine documentation and NuGet dependency updates.
- Now supports generic keys.
- Applied patch for issue #14.
- Now built for .Net 8, and removed support for 6 and 7.
- Updated NuGet packages to latest releases.
- Added support for .Net 6 and .Net 7.
- Addressing bug #9, implemented interfaces IUserAuthenticatorKeyStore and IUserTwoFactorRecoveryCodeStore to support two factor authentication. Example website updated to demonstrate capability with QR code generation.
- Introduced support for
IUserLoginStore<TUser>
in User Store
- Introduced support for
IUserPhoneNumberStore<TUser>
in User Store
- Introduced support for
IUserEmailStore<TUser>
in User Store
- Forked from source repository pierodetomi/efcore-identity-cosmos.
- Refactored for .Net 6 LTS.
- Added
UserStore
,RoleStore
,UserManager
andRoleManager
unit tests. - Namespace changed to one more generic:
AspNetCore.Identity.CosmosDb
- Implemented
IUserLockoutStore
interface forUserStore
- Added example web project
- Implemented IQueryableUserStore and IQueryableRoleStore
To run the unit tests you will need two things: (1) A Cosmos DB Account, and (2) a connection string to that account.
Here is an example of a secrets.json
file created for the unit test project:
{
"CosmosIdentityDbName" : "YOURDATABASENAME",
"ConnectionStrings": {
"ApplicationDbContextConnection": "AccountEndpoint=YOURCONNECTIONSTRING;"
}
}
This implementation will work with the "Free" Cosmos DB tier. You can have one per account.
It also works the "serverless" and "provisioned" account types.
To learn more about Asp.Net Identity and items realted to this project, please see the following: