如何使用UserManager
或SignInManager
调用现有的Login存储过程?是否可以使用现有的数据库结构,并想从存储过程中创建授权和身份验证?
但是当我根据自己的要求使用时,会出现错误:
[Route("api/[controller]")]
[ApiController]
[AllowAnonymous]
public class AuthenticateController : ControllerBase
{
private readonly UserManager<ApplicationUser> userManager;
private readonly RoleManager<IdentityRole> roleManager;
private readonly IConfiguration _configuration;
private readonly ISqlApplicationUserRepository sqlApplicationUserRepository;
public AuthenticateController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, IConfiguration configuration, ISqlApplicationUserRepository sqlApplicationUserRepository)
{
this.userManager = userManager;
this.roleManager = roleManager;
_configuration = configuration;
this.sqlApplicationUserRepository = sqlApplicationUserRepository;
}
[HttpPost]
[Route("login")]
public async Task<IActionResult> Login(SiteUser model)
{
//this function i want to use instead of .FindByNameAsync
var user1 = sqlApplicationUserRepository.GetUserProfile(model.UserName);//this function i want to use instead of .FindByNameAsync
var user = await userManager.FindByNameAsync(model.UserName);
//so what change i need to do in this section ir in signinmanager to authenticate my user from membership tables using store procedure.
if (user1 != null && await userManager.CheckPasswordAsync(user1, model.Password))
{
var userRoles = await userManager.GetRolesAsync(user1);
var authClaims = new List<Claim>
{
new Claim(ClaimTypes.Name, user1.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
foreach (var userRole in userRoles)
{
authClaims.Add(new Claim(ClaimTypes.Role, userRole));
}
var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));
var token = new JwtSecurityToken(
issuer: _configuration["JWT:ValidIssuer"],
audience: _configuration["JWT:ValidAudience"],
expires: DateTime.Now.AddHours(3),
claims: authClaims,
signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
});
}
return Unauthorized();
}
}