我找不到任何关于这个的好文档,但是我必须实现同样的功能,所以我通过修改标准ASP.NET身份验证模板中的操作来编写了REST API。
例如,这就是我如何处理登录操作:
[HttpPost("[action]")]
[AllowAnonymous]
public async Task<ReturnValue<ApplicationUser>> Login([FromBody] loginModel login)
{
if (ModelState.IsValid)
{
ApplicationUser user = await _userManager.FindByEmailAsync(login.email);
if (user == null)
{
return new ReturnValue<ApplicationUser>(false, "Login failed, check username and password.", null);
}
else
{
var result = await _signInManager.PasswordSignInAsync(user, login.password, (bool)login.rememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return new ReturnValue<ApplicationUser>(true, user);
}
if (result.IsLockedOut)
{
return new ReturnValue<ApplicationUser>(false, "The account is locked out.", null);
}
}
}
else
{
string message = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
return new ReturnValue<ApplicationUser>(false, "Invalid login attempt: " + message, null);
}
return new ReturnValue<ApplicationUser>(false, "Login failed.", null);
}
如果您从浏览器内的javascript调用API,那么cookie将被加载,您应该能够进一步授权调用API。如果您从其他类型的客户端调用,则需要确保CookieContainer保留以进行授权调用。
从这个点开始,您可以使用标准Microsoft库通过[Authorize]修饰符来授权您的REST API控制器:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity
祝好运。
无状态(Stateless)
是最好的选择。实质上,您需要在每个请求中发送身份验证有效载荷数据,这将允许您确定请求可以访问什么和不能访问什么。请参见:http://www.developerhandbook.com/c-sharp/create-restful-api-authentication-using-web-api-jwt/ - scgough