我已按照以下帖子中提到的解决方案,使用ASP.Net Core实现了Web API的令牌身份验证 Token Based Authentication in ASP.NET Core
为了实现身份验证逻辑,我已经定义了以下方法
public async Task<bool> AuthenticateUser(string email, string password)
{
UserManager<ApplicationUser> _userManager = HttpContext.ApplicationServices.GetService(typeof(UserManager<ApplicationUser>)) as UserManager<ApplicationUser>;
SignInManager<ApplicationUser> _signInManager = HttpContext.ApplicationServices.GetService(typeof(SignInManager<ApplicationUser>)) as SignInManager<ApplicationUser>;
var result = await _signInManager.PasswordSignInAsync(email, password, isPersistent: false, lockoutOnFailure: false);
if (result.Succeeded)
{
return true;
}
else
{
return false;
}
}
并且调用Post方法是
[HttpPost]
public dynamic Post([FromBody] AuthRequest req)
{
string email = req.username;
string password = req.password;
try
{
bool isAuthenticated = false;
//implement the authentication logic over here
isAuthenticated = AuthenticateUser(email, password).Result;
if (isAuthenticated)
{
DateTime? expires = DateTime.UtcNow.AddDays(2);
var token = GetToken(req.username, expires);
return new { authenticated = true, entityId = 1, token = token, tokenExpires = expires };
}
}
catch (Exception ex)
{
return new { authenticated = false, message = "Exception: " + ex.Message, detailedmessage = ex.InnerException};
}
return new { authenticated = false };
}
现在问题......
Post在第一次调用时执行正常并返回所需的结果,但是,在第二次调用时,它会抛出异常
没有配置身份验证处理程序来处理该方案:Microsoft.AspNet.Identity.Application
在调试时,我发现在执行以下行时抛出了这个异常
var result = await _signInManager.PasswordSignInAsync(email, password, isPersistent: false, lockoutOnFailure: false);
第一次调用时工作正常,但在所有后续调用中抛出异常。
过去2天我一直在搜索此问题,我发现在Startup.cs app.UseIdentity();应该在添加身份验证中间件之前调用。它已经在我的代码中发生了。
请建议我在这里缺少什么。