Skip to content

Instantly share code, notes, and snippets.

@pericles97
Last active October 21, 2020 00:09
Show Gist options
  • Save pericles97/03948d17fe93a4098a93c7967d0a42bb to your computer and use it in GitHub Desktop.
Save pericles97/03948d17fe93a4098a93c7967d0a42bb to your computer and use it in GitHub Desktop.
I got this error “Unable to resolve service for type AspNetCore.Identity.SignInManager” when I use ApplicationUser instead IdentityUser
/*I have a .NET Core 3.1 Web Api and I created an ApplicationUser class that inherits from IdentityUser because I need to register some others properties. But when I attempt to register a new user I get the following error:
Unable to resolve service for type 'Microsoft.AspNetCore.Identity.SignInManager[MyProject.Api.ApplicationUser]' while attempting to activate 'MyProject.Api.Controllers.AuthController'.*/
/*Here's the IdentityConfig class that set the dependencys on Startup class:*/
public static class IdentityConfig
{
public static IServiceCollection AddIdentityConfig(this IServiceCollection services,
IConfiguration configuration)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddErrorDescriber<IdentityMensagensPortugues>()
.AddDefaultTokenProviders();
var appSettingsSection = configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = true;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = appSettings.ValidoEm,
ValidIssuer = appSettings.Emissor
};
});
return services;
}
}
/*Here's the ApplicationDbContext class:*/
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
}
/*Here's the Controller class:*/
public class AuthController : MainController
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly AppSettings _appSettings;
private readonly ILogger _logger;
public AuthController(INotificator notificator,
SignInManager<ApplicationUser> signInManager,
UserManager<ApplicationUser> userManager,
IOptions<AppSettings> appSettings,
IUser user, ILogger<AuthController> logger) : base(notificator, user)
{
_signInManager = signInManager;
_userManager = userManager;
_logger = logger;
_appSettings = appSettings.Value;
}
[HttpPost("new-account")]
public async Task<ActionResult> Register(RegisterUserViewModel registerUser)
{
if (!ModelState.IsValid) return CustomResponse(ModelState);
ApplicationUser user = new ApplicationUser {
UserName = registerUser.Email,
Email = registerUser.Email,
Cpf = registerUser.Cpf,
ZipCode = registerUser.ZipCode,
Gender = registerUser.Gender,
EmailConfirmed = true
};
var result = await _userManager.CreateAsync(user, registerUser.Password);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, false);
return CustomResponse(await GerarJwt(user.Email));
}
foreach (var error in result.Errors)
{
NotifyError(error.Description);
}
return CustomResponse(registerUser);
}
[HttpPost("enter")]
public async Task<ActionResult> Login(LoginUserViewModel loginUser)
{
if (!ModelState.IsValid) return CustomResponse(ModelState);
var result = await _signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Password, false, true);
if (result.Succeeded)
{
_logger.LogInformation("User "+ loginUser.Email +" successfully logged in");
return CustomResponse(await GerarJwt(loginUser.Email));
}
if (result.IsLockedOut)
{
NotifyError("User temporarily blocked by invalid attempts");
return CustomResponse(loginUser);
}
NotificarErro("User or Password incorrect");
return CustomResponse(loginUser);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment