我目前正在学习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