AspNetCore.Identity.CosmosDb 2.1.3

There is a newer version of this package available.
See the version list below for details.
dotnet add package AspNetCore.Identity.CosmosDb --version 2.1.3                
NuGet\Install-Package AspNetCore.Identity.CosmosDb -Version 2.1.3                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AspNetCore.Identity.CosmosDb" Version="2.1.3" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add AspNetCore.Identity.CosmosDb --version 2.1.3                
#r "nuget: AspNetCore.Identity.CosmosDb, 2.1.3"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install AspNetCore.Identity.CosmosDb as a Cake Addin
#addin nuget:?package=AspNetCore.Identity.CosmosDb&version=2.1.3

// Install AspNetCore.Identity.CosmosDb as a Cake Tool
#tool nuget:?package=AspNetCore.Identity.CosmosDb&version=2.1.3                

Cosmos DB Provider for ASP.NET Core Identity

CodeQL Net6.0 Tests Net7.0 Tests NuGet

This is a Cosmos DB implementation of an Identity provider for .NET 6 and 7 that uses the "EF Core Azure Cosmos DB Provider.".

Installation

Add the following NuGet package to your project:

PM> Install-Package AspNetCore.Identity.CosmosDb

Create an Azure Cosmos DB account - either the serverless or dedicated instance. For testing and development purposes it is recommended to use a 'serverless instance' as it is very economical to use. See documentation to help choose which 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"
  }
}

Update Database Context

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>
    {
        public ApplicationDbContext(DbContextOptions dbContextOptions)
          : base(dbContextOptions) { }
    }
}

Modify Program.cs or Startup.cs File

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;
using AspNetCore.Identity.Services.SendGrid;
using AspNetCore.Identity.Services.SendGrid.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>(
      options => options.SignIn.RequireConfirmedAccount = true // Always a good idea :)
    )
    .AddDefaultUI() // Use this if Identity Scaffolding is in use
    .AddDefaultTokenProviders();

Configure Email Provider (Optional)

When users register accounts or need to reset passwords, you will need (at a minimum), the ability to send tokens via an Email provider. The example below uses a SendGrid provider. Here is how to add it:

Start by adding the following NuGet package to your project:

PM> Install-Package AspNetCore.Identity.Services.SendGrid

Note: You can sign up for a free SendGrid account if you do not already have one.

Configure app to support email

Next we need to configure the application to support our Email provider. Start by adding the following code to your startup file:

var sendGridApiKey = builder.Configuration.GetValue<string>("SendGridApiKey");
// Modify 'from' email address to your own.
var sendGridOptions = new SendGridEmailProviderOptions(sendGridApiKey, "foo@mycompany.com");

builder.Services.AddSendGridEmailProvider(sendGridOptions);

Modify "Scaffolded" Identity UI

The example web project uses the "scaffolded" Identity UI. By default it does not use an IEmailProvider. But in our case we have installed one so we need to modify the UI to enable it.

In your project, find this file:

/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs

Find the OnGetAsync() method, then look for the following line:

DisplayConfirmAccountLink = true;

Change that line to false like the following:

DisplayConfirmAccountLink = false;

Complete Startup File Example

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.

Supported LINQ Operators User and Role Stores

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.

Help Find Bugs!

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!

Changelog

v2.1.1

  • Added support for .Net 6 and .Net 7.

v2.0.20

  • Addressing bug #9, implemented interfaces IUserAuthenticatorKeyStore and IUserTwoFactorRecoveryCodeStore to support two factor authentication. Example website updated to demonstrate capability with QR code generation.

v1.0.6

  • Introduced support for IUserLoginStore<TUser> in User Store

v1.0.5

  • Introduced support for IUserPhoneNumberStore<TUser> in User Store

v1.0.4

  • Introduced support for IUserEmailStore<TUser> in User Store

v2.0.0-alpha

  • Forked from source repository pierodetomi/efcore-identity-cosmos.
  • Refactored for .Net 6 LTS.
  • Added UserStore, RoleStore, UserManager and RoleManager unit tests.
  • Namespace changed to one more generic: AspNetCore.Identity.CosmosDb
  • Implemented IUserLockoutStore interface for UserStore

v2.0.1.0

  • Added example web project

v2.0.5.1

  • Implemented IQueryableUserStore and IQueryableRoleStore

Unit Test Instructions

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;"
  }
}

Choice of Cosmos DB Account Type

Because this implementation uses multiple containers, it exceeds the minimum throughput requirements for the "free" Cosmos DB account.

However, if you deploy a "serverless" account, your monthly costs will be very low. For example, our serverless Cosmos account used for unit testing costs under $0.10 (US) a month as of July 2022.

References

To learn more about Asp.Net Identity and items realted to this project, please see the following:

Product 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 is compatible.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on AspNetCore.Identity.CosmosDb:

Package Downloads
Cosmos.Cms.Common

This package contains all the common methods and objects used by the Cosmos CMS editor website, and by any website service the role of a publishing website.

Cosmos.Common

This package contains all the common methods and objects used by the Cosmos CMS editor website, and by any website service the role of a publishing website.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
8.0.7 2,467 9/3/2024
8.0.6 2,524 5/29/2024
8.0.4 577 4/18/2024
8.0.3 846 3/12/2024
8.0.2 1,015 2/15/2024
8.0.1 1,440 1/12/2024
8.0.0 869 12/18/2023
8.0.0-rc.3 78 12/15/2023
2.1.4 7,305 1/30/2023
2.1.3 673 12/15/2022
2.1.2 493 11/16/2022
2.1.1 511 11/11/2022
2.0.22 404 11/9/2022
2.0.21 404 11/6/2022
2.0.20 1,300 10/27/2022
2.0.19-rc 158 10/26/2022
2.0.18 895 9/24/2022
2.0.17 413 9/5/2022
2.0.16 715 8/24/2022
2.0.15 479 8/13/2022
2.0.14 412 8/11/2022
2.0.13 451 8/8/2022
2.0.12 460 7/31/2022
2.0.11 462 7/23/2022
2.0.10 474 7/13/2022
2.0.9 449 7/12/2022
2.0.8 478 7/12/2022
2.0.7 455 7/8/2022
2.0.6 457 7/8/2022
2.0.5.1 462 7/6/2022
2.0.4 466 7/5/2022
2.0.3.3 461 7/4/2022
2.0.3.2 484 7/3/2022
2.0.3.1 483 7/3/2022
2.0.2.1 474 7/1/2022
2.0.1-alpha 194 6/30/2022
2.0.0-alpha 205 6/25/2022

Nuget dependencies and documentation update.