Brian McBride

Brian McBride

  • 1.7k
  • 9
  • 671

Blazor C# PasswordHasher.VerifyPassword Permanently Returning Fail

Dec 1 2023 8:15 AM

In my Blazor server app, I'm having difficulty authenticating a user's password, after having previously created it using the same password. The example below depicts the password ("testing_01") being originally created and hashed using PasswordHasher.HashPassword. Thereafter, I attempt to verify that same password using PasswordHasher.VerifyPassword. It permanently returns the message "Login Failed". I'm clearly doing something wrong.

As I'm using the same password, I would have expected the simple example to have returned "Login Succeeded".

Any help appreciated.

@page "/test"
@using System;
@using Microsoft.AspNetCore.Components;
@using Microsoft.Extensions.Logging;

@inject ILogger<PasswordService> Logger

@code {
    [Inject]
    public NavigationManager NavigationManager { get; set; }

    public class PasswordService
    {
        private readonly ILogger<PasswordService> _logger;
        private PasswordHasher<object> passwordHasher = new PasswordHasher<object>();

        public PasswordService(ILogger<PasswordService> logger)
        {
            _logger = logger;
        }

        public (string hashedPassword, byte[] salt) HashPasswordWithSalt(string password)
        {
            byte[] salt = new byte[16]; // Generate a random salt (you may use a proper method to generate a secure random salt)
            new Random().NextBytes(salt);

            var hashedPassword = passwordHasher.HashPassword(null, password + Convert.ToBase64String(salt));

            return (hashedPassword, salt);
        }

        public bool VerifyPassword(string password, string hashedPassword, byte[] salt)
        {
            // Concatenate user input password and stored salt, then hash
            var inputHashedPassword = passwordHasher.HashPassword(null, password + Convert.ToBase64String(salt));

            // Verify hashed password
            var result = passwordHasher.VerifyHashedPassword(null, hashedPassword, inputHashedPassword);

            return result == PasswordVerificationResult.Success;
        }

        public void LogTest(string msg)
        {
            _logger.LogInformation(msg);
        }
    }

    protected override void OnInitialized()
    {
        var passwordService = new PasswordService(Logger);

        // Simulate user registration
        var userInputPassword = "testing_01";
        var (storedHashedPassword, storedSalt) = passwordService.HashPasswordWithSalt(userInputPassword);

        // Simulate user login
        var loginResult = passwordService.VerifyPassword(userInputPassword, storedHashedPassword, storedSalt);

        if (loginResult)
        {
            passwordService.LogTest("Login Succeeded");
        }
        else
        {
            passwordService.LogTest("Login Failed");
        }
    }
}

 


Answers (2)