我找不到任何好的文檔,但是我必須實現相同的功能,所以我通過將標準ASP.NET身份驗證模板中的操作修改爲REST API等價物來編寫其餘的api。
比如這裏是我工作過的登錄操作:
// POST: /Account/Login
[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 if (user.EmailConfirmed == false)
// {
// return new ReturnValue<ApplicationUser>(true, "Confirm email address.", null, user);
// }
else
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(user, login.password, (bool)login.rememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return new ReturnValue<ApplicationUser>(true, user);
}
//if (result.RequiresTwoFactor)
//{
// return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
//}
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);
}
// If we got this far, something failed in the model.
return new ReturnValue<ApplicationUser>(false, "Login failed.", null);
}
如果調用瀏覽器中通過JavaScript API的餅乾將被加載,你應該能夠作出進一步的授權調用的API,如果您從其他類型的客戶端進行調用,則需要確保CookieContainer保留用於授權調用。
從這一點你可以使用[授權]裝飾通過標準的Microsoft庫授權您的REST API控制器:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity
好運。
我發現[this](https://samueleresca.net/2016/12/developing-token-authentication-using-asp-net-core/)非常有幫助,不確定它是否是你正在尋找的東西。 –
我會說'無狀態'是要走的路。實質上,您需要在每次請求時發送auth有效內容數據,這將允許您確定請求可以訪問和不可訪問的內容。看到這個:http://www.developerhandbook.com/c-sharp/create-restful-api-authentication-using-web-api-jwt/ – scgough
@邁克爾愛德華我只是在以前同樣的事情賞金,請參閱這個[question](http://stackoverflow.com/q/42121854/1938988)及其答案 –