我目前正在學習ASP.NET 5的Web API,因此實現了一個非常簡單的應用程序,包括用戶身份驗證/身份框架驗證。ASP.NET 5(vNext)Web API:如何構建授權標頭?
我的AccountController的登錄方法,可處理註冊和登錄看起來是這樣的:
[HttpPost("[action]/{username};{password}")]
public async Task<IActionResult> Login(string username, string password)
{
var result = await _signInManager.PasswordSignInAsync(username, password, false, lockoutOnFailure: false);
if (result.Succeeded)
{
Logger.LogInformation(1, "User logged in.");
return new HttpOkResult();
}
return new BadRequestResult();
}
當我進行登錄,我得到它包含一個cookie,看起來像這樣的HTTP結果:
Set-Cookie: .AspNet.Microsoft.AspNet.Identity.Application=CfDJ8 [...] 2XQ; path=/; httponly
我認爲,每當我想要訪問控制器或裝有某種[授權]屬性的控制器或方法時,cookie都包含我必須添加到HTTP請求中的令牌。
但是,我不確定如何包含此令牌的有效HTTP請求看起來像。我曾嘗試以下要求它沒有做的伎倆:
GET http://localhost:9466/api/videogames/GetAll HTTP/1.1
User-Agent: Fiddler
Host: localhost:9466
Authorization: bearer CfDJ8 [...] 2XQ
也許從失敗的授權以下日誌摘要可能會有所幫助:
[10.03.2016 12:44:30] Information: [Microsoft.AspNet.Hosting.Internal.HostingEngine] Request starting HTTP/1.1 GET http://localhost:9466/api/videogames/GetAll
[10.03.2016 12:44:30] Warning: [Microsoft.AspNet.Mvc.Controllers.ControllerActionInvoker] Authorization failed for the request at filter 'Microsoft.AspNet.Mvc.Filters.AuthorizeFilter'.
[10.03.2016 12:44:30] Information: [Microsoft.AspNet.Authentication.Cookies.CookieAuthenticationMiddleware] AuthenticationScheme: Microsoft.AspNet.Identity.Application was challenged.
[10.03.2016 12:44:30] Information: [Microsoft.AspNet.Mvc.ChallengeResult] Executing ChallengeResult with authentication schemes().
[10.03.2016 12:44:30] Information: [Microsoft.AspNet.Mvc.Infrastructure.MvcRouteHandler] Executed action VideoGameStoreWebApi.Controllers.VideoGamesController.GetAll in 0ms
[10.03.2016 12:44:30] Information: [Microsoft.AspNet.Hosting.Internal.HostingEngine] Request finished in 0ms 302
[10.03.2016 12:44:30] Information: [Microsoft.AspNet.Hosting.Internal.HostingEngine] Request starting HTTP/1.1 GET http://localhost:9466/Account/Login?ReturnUrl=%2Fapi%2Fvideogames%2FGetAll
[10.03.2016 12:44:30] Information: [Microsoft.AspNet.Hosting.Internal.HostingEngine] Request finished in 0ms 404
是否有我怎麼加了一個錯誤令牌到HTTP請求還是有一個更基本的問題在身份框架如何處理我不知道的用戶授權?
在此先感謝您的答案!
謝謝您的回答如何設置身份驗證和授權網絡的API,它幫了我很多的全樣本。您的示例引用了Web API 2.2,而不是針對ASP.NET 5引入的版本,但經過一些額外的研究後,我發現了這篇文章:[link](https:// stackoverflow。com/questions/29048122/token-based-authentication-in-asp-net-5-vnext/29698502#29698502) 雖然我仍然無法連接密碼驗證在使用身份框架管理用戶的令牌請求期間(我目前不確定如何檢查給定的用戶名和密碼是否是現有用戶) – Kerl