Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a custom SignInManager in Asp.Net Core 3 Identity

I want to create a custom class for my SignInManager, so I've created a class that inherts from SignInManager<> as follows:

public class ApplicationSignInManager : SignInManager<ApplicationUser>
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly ApplicationDbContext _dbContext;
    private readonly IHttpContextAccessor _contextAccessor;

    public ApplicationSignInManager(
UserManager<ApplicationUser> userManager,
        IHttpContextAccessor contextAccessor,
        IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory,
        IOptions<IdentityOptions> optionsAccessor,
        ILogger<SignInManager<ApplicationUser>> logger,
        ApplicationDbContext dbContext,
        IAuthenticationSchemeProvider schemeProvider
        )
        : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemeProvider)
    {
        _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
        _contextAccessor = contextAccessor ?? throw new ArgumentNullException(nameof(contextAccessor));
        _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
    }
}

and then I've added it in the services configuration in Startup.cs:

services.AddDefaultIdentity<ApplicationUser>(configure =>
{
    configure.User.AllowedUserNameCharacters += " ";
}).AddSignInManager<ApplicationSignInManager>()
  .AddDefaultUI(UIFramework.Bootstrap4)
  .AddEntityFrameworkStores<ApplicationDbContext>();

The problem is that the default SignInManager<ApplicationUser> cannot be casted to a ApplicationSignInManager, so I get this error when accessing a page in whose controller the manager is injected:

InvalidCastException: Unable to cast object of type 'Microsoft.AspNetCore.Identity.SignInManager`1[Socialize.Data.ApplicationUser]' to type 'Socialize.Utilities.Identity.ApplicationSignInManager'.

like image 325
iRealWorlds Avatar asked Mar 05 '23 07:03

iRealWorlds


1 Answers

Your issue is caused by that you register AddSignInManager<ApplicationSignInManager>() before .AddDefaultUI(UIFramework.Bootstrap4).

For AddDefaultUI, it will call builder.AddSignInManager(); which will register the typeof(SignInManager<>).MakeGenericType(builder.UserType) and will override your previous settings.

Try Code below:

        services.AddDefaultIdentity<ApplicationUser>()                
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddSignInManager<ApplicationSignInManager>();
like image 61
Edward Avatar answered Mar 23 '23 14:03

Edward