Skip to content
  • English Deutsch

benjamin-abt.com

Performance is a feature | Cloud - AI - Azure - .NET - Sustainability

  • Home
  • Blog
  • Portfolio
    • Overview
    • Workshops & Training
    • Publications
  • Contact
  • Home
  • Blog

Custom PasswordHasher in ASP.NET Core Identity

Custom PasswordHasher in ASP.NET Core Identity
December 16, 2019 3 min read BEN ABT
.NET ASP.NET Core

This article was written in 2019. Versions, tools and recommendations may have changed since then. Newer posts are collected under .NET.

In the ASP.NET Core Identity environment, the PasswordHasher is responsible for securely storing the password and performing password entry checks.

In this respect, the PasswordHasher is also responsible for choosing the correct hash method, whereby several hash methods can be used.

First Byte

In the world of ASP.NET Core Identity, the first byte of the password has a special meaning: it indicates how the password was hashed.

  • 0x00 - Version 2: PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
  • 0x01 - Version 3: PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.

See more details here: PasswordHasher.cs Source

The peculiarity of the first byte can now be used to store own implementations for hashing. This is especially useful for migrating passwords.
However, care must be taken that no reserved byte representations are used for own implementations.

Password Migrations

ASP.NET Core Identity has a built-in mechanism for migrating (e.g. re-hashing) passwords.

The idea is that users enter their password and the verification process determines if the password hash system is out of date. If it is outdated, the password is automatically re-hashed and saved with the currently defined mechanism.

As a result, users do not notice the hash system update and do not need to be prompted for a reset.

At this moment the system is informed that the password has been successfully verified, but that a re-hash is necessary. The identity system takes care of the rest completely automatically.

Rehash mechanism

The re-hash mechanism works as follows:

The password check determines whether the password is “valid”, “invalid” or “valid, with obsolete mechanism”.
The latter is represented by the enum SuccessRehashNeeded.

The result arrives at the “UserManager” of the identity implementation, which automatically updates the password in the event of a necessary rehash.

C#
 1public class PortalUserManager : UserManager<PortalUser>
 2{
 3    private readonly IUserPasswordStore<PortalUser> _passwordStore;
 4
 5    public PortalUserManager(
 6        IUserStore<PortalUser> store,
 7        IOptions<IdentityOptions> optionsAccessor,
 8        IPasswordHasher<PortalUser> passwordHasher,
 9        IEnumerable<IUserValidator<PortalUser>> userValidators,
10        IEnumerable<IPasswordValidator<PortalUser>> passwordValidators,
11        ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors,
12        IServiceProvider services, ILogger<UserManager<PortalUser>> logger) : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger)
13    {
14        _passwordStore = Store as IUserPasswordStore<PortalUser>;
15    }
16
17    public override async Task<bool> CheckPasswordAsync(PortalUser user, string password)
18    {
19        if (user is null) { return false; }
20
21        // Verify users password
22        PasswordVerificationResult result = await VerifyPasswordAsync(_passwordStore, user, password);
23
24        // if reshash is required, automatically rehash the password
25        if (result == PasswordVerificationResult.SuccessRehashNeeded)
26        {
27            await UpdatePasswordHash(user, password, validatePassword: false);
28            await UpdateUserAsync(user);
29        }
30
31        bool success = result != PasswordVerificationResult.Failed;
32        if (!success)
33        {
34                Logger.LogWarning(0, $"Invalid password for user {user.Id}.");
35        }
36        return success;
37    }
38}

Sample

C#
 1public class PortalUserPasswordHasher : PasswordHasher<PortalUser>, IPasswordHasher<PortalUser>
 2{
 3    public PortalUserPasswordHasher(
 4        IOptions<PasswordHasherOptions> optionsAccessor = null) 
 5        : base(optionsAccessor) { }
 6
 7    /// </summary>
 8    public override PasswordVerificationResult VerifyHashedPassword(
 9        PortalUser user, string hashedPassword, string providedPassword)
10    {
11        // pass as bytes
12        byte[] decodedHashedPassword = Convert.FromBase64String(hashedPassword);
13
14        // we check the first byte
15        //    this byte indicates which hash algorithm is used
16        switch (decodedHashedPassword[0])
17        {
18            // if it's old (old PHP platform), request rehash on success
19            case PortalUserHashHelper.PhpBBFormatMarker:
20                if (LegacyPhpBBPasswordProvider.VerifyHashedPassword(
21                                    decodedHashedPassword, providedPassword))
22                {
23                    return PasswordVerificationResult.SuccessRehashNeeded;
24                }
25                else
26                {
27                    return PasswordVerificationResult.Failed;
28                }
29
30            // otherwise we use the default ASP.NET Core Identity behavior
31            default:
32                return base.VerifyHashedPassword(user, hashedPassword, providedPassword);
33        }
34    }
35}

Related articles

Production Rate Limiting in ASP.NET Core

Nov 3, 2026 - 16 min read

Production Rate Limiting in ASP.NET Core

Most ASP.NET Core rate-limiting examples stop after registering a fixed window. That is enough to demonstrate the middleware, but it is not …

Problem Details in ASP.NET Core and .NET 11

Oct 5, 2026 - 12 min read

Problem Details in ASP.NET Core and .NET 11

builder.Services.AddProblemDetails() registers infrastructure. It does not create an error contract. An ASP.NET Core request can fail during …

Resilience in .NET with Microsoft.Extensions.Resilience

Sep 21, 2026 - 11 min read

Resilience in .NET with Microsoft.Extensions.Resilience

Retries are the most visible resilience strategy and the easiest one to misuse. Repeating a failing call can recover from a short network …


BEN ABT

BEN ABT

Ben is Chief Engineering Officer and Principal Software Engineer at Medialesson.de, with a strong focus on .NET and Microsoft Azure. In his professional role, he designs and builds highly scalable platforms for hybrid and cloud-based scenarios. He also advises companies and C-levels on migrating to the sovereign cloud.

He runs myCSharp.de, the largest and most active German-speaking C# community forum, actively contributes to both his own and external open-source projects and regularly shares his knowledge through his blog, at community events, conferences and as a writer for technical magazines.

Let's Work Together

Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.

New Platforms

Modernization

Training & Consulting

Contact Me
X Facebook LinkedIn WhatsApp
Back Next Blog Post

Open for work!

Contact Me
BEN ABT BEN ABT Software Engineer · Microsoft MVP Passionate about .NET, Azure, performance optimization and sustainable software engineering.

Medialesson GmbH Logo

Microsoft MVP Logo

Recent posts

View all
Production Rate Limiting in ASP.NET Core

Production Rate Limiting in ASP.NET Core

Nov 3, 2026
The Big Decimal Bugfix with .NET 11

The Big Decimal Bugfix with .NET 11

Nov 2, 2026
Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Distroless, Chiseled or Alpine: Choosing a .NET Base Image

Oct 27, 2026
Stop Using nginx as Your Default Static File Server in Docker

Stop Using nginx as Your Default Static File Server in …

Oct 24, 2026
Containerizing .NET in 2026 Without a Dockerfile

Containerizing .NET in 2026 Without a Dockerfile

Oct 20, 2026

Tags

.NET (195) Csharp (99) ASP.NET Core (49) Azure (41) DevOps (17) Docker (15) Microsoft (14) EF Core (11) Microsoft MVP (11) Security (11) AI (10) GitHub (10) GitHub Copilot (10) ASP.NET (9) Synology (9) .NET 11 (8) Architecture (8) Raspberry (8) Azure Functions (7) Cloudflare (7)
benjamin-abt.com

About BEN

Benjamin Abt is a Software Engineer, Platform Architect and Microsoft MVP specializing in .NET, Azure, cloud architecture, performance optimization and sustainable software development.

Connect

  • Follow me on GitHub
  • Follow me on LinkedIn
  • Follow me on Mastodon
  • Microsoft MVP profile
  • Follow SchwabenCode on GitHub
  • Follow me on X

Quick Links

  • Portfolio
  • Blog
  • Workshops & Training
  • Publications
  • Get in Touch
  • Sitemap
Open for Work

© Copyright Benjamin Abt & SchwabenCode | 2011 - 2026

Content licensed under CC BY 4.0 unless otherwise noted.

  • Impressum
  • Privacy
  • Contact