我使用ASP实现了Web API的令牌身份验证。遵循以下帖子中提到的解决方案基于令牌的ASP认证。网络核心
为了实现身份验证逻辑,我定义了以下方法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();应在添加身份验证中间件之前调用。它已经在我的代码中发生了。
将AuthenticateUser()方法中的HttpContext.ApplicationServices.GetService()改为HttpContext.RequestServices.GetService()。我的更新方法是
public async Task<bool> AuthenticateUser(string email, string password)
{
UserManager<ApplicationUser> _userManager = HttpContext.RequestServices.GetService(typeof(UserManager<ApplicationUser>)) as UserManager<ApplicationUser>;
SignInManager<ApplicationUser> _signInManager = HttpContext.RequestServices.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;
}
}