Creating a custom SignInManager in Asp.Net Core 3 Identity

情到浓时终转凉″ 提交于 2020-03-01 06:37:29

问题


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'.


回答1:


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>();


来源:https://stackoverflow.com/questions/55230614/creating-a-custom-signinmanager-in-asp-net-core-3-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!