Login not possible with AspNetCore Idenity when Enable DataProtection.

Nero Rodrigues 0 Reputation points
2025-02-27T21:16:42.94+00:00

I'm configuring my application to make use of AspNetCore.Identity as well Data protection.

	public static void Main(string[] args)
    {
		var builder = WebApplication.CreateBuilder(args);
		builder.Services
			.AddIdentityApiEndpoints<IdentityUser<Guid>>(options =>
			{
		   		options.Stores.ProtectPersonalData = true;
	    	})
			.AddPersonalDataProtection<LookupProtector, LookupProtectorKeyRing>();
		builder.Services.AddDataProtection();
    	builder.Services.AddOptions<KeyManagementOptions>()
	   		.Configure<IServiceScopeFactory>((options, factory) =>
       		{
       			options.XmlRepository = new CustomXmlRepository(factory);
       		});	
		...
	}

When running the application I can register new users through the Api without a problem, however when I try to login I always get a 401 - Unauthorized. During the debugging I see that every time i send a new login request the I hit the implementation of ILookupProtector which will protect the username and will be user by user manager to retrieve the user record, however the protected value is never the same and in this case the query to get the user will return nothing.

The current documentation from AspNetCore Identity doesn't cover any information regarding the use of protected Data.

public class LookupProtector : ILookupProtector
{
    private readonly IDataProtectionProvider _dataProtectorProvider;
    public LookupProtector(IDataProtectionProvider dataProtectorProvider)
    {
        _dataProtectorProvider = dataProtectorProvider;
    }
    [return: NotNullIfNotNull("data")]
    public string? Protect(string keyId, string? data)
    {
        if (string.IsNullOrWhiteSpace(data)) return data;
        return dataProtector.CreateProtector(keyId).Protect(data);
    }
    [return: NotNullIfNotNull("data")]
    public string? Unprotect(string keyId, string? data)
    {
        if (string.IsNullOrWhiteSpace(data)) return data;
        return _dataProtectorProvider.CreateProtector(keyId).Unprotect(data);
    }
}
Developer technologies | ASP.NET | ASP.NET API
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2025-02-28T07:34:00.23+00:00

    Hi,@Nero Rodrigues

    You may register your services follow this document:

    builder.Services .AddIdentityApiEndpoints<IdentityUser<Guid>>
    (options => 
    {
     options.Stores.ProtectPersonalData = true; 
     options.Stores.MaxLengthForKeys = 128;
    })
    services.AddScoped<ILookupProtectorKeyRing, KeyRing>();
    services.AddScoped<ILookupProtector, LookupProtector>();
    

    To have Identity encrypt your custom IdentityUser model, annotate your model fields with [ProtectedPersonalData].

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.