ASP.NET 5(vNext)Web API:如何构建授权头?
我目前正在学习ASP.NET 5的Web API,因此实现了一个非常简单的应用程序,包括使用Identity framework进行用户授权/身份验证 my AccountController处理注册和登录的登录方法如下所示:ASP.NET 5(vNext)Web API:如何构建授权头?,asp.net,cookies,header,authorization,identity,Asp.net,Cookies,Header,Authorization,Identity,我目前正在学习ASP.NET 5的Web API,因此实现了一个非常简单的应用程序,包括使用Identity framework进行用户授权/身份验证 my AccountController处理注册和登录的登录方法如下所示: [HttpPost("[action]/{username};{password}")] public async Task<IActionResult> Login(string username, string password) {
[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();
}
Set-Cookie: .AspNet.Microsoft.AspNet.Identity.Application=CfDJ8 [...] 2XQ; path=/; httponly
我假设,cookie包含每当我想要访问某种[Authorize]属性修饰的控制器或方法时必须添加到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请求中是否存在错误,或者在identity framework如何处理我不知道的用户授权方面是否存在更基本的问题
提前感谢您的回答 在web API中使用安全性的推荐方法是将OAuth2与承载令牌一起使用 设置的问题在于,您试图将表单身份验证与基于令牌的身份验证相结合 要在web API中使用承载令牌,您需要在web API中设置令牌服务(也称为STS或授权服务器),或者使用一些外部令牌服务(如google或facebook) 使用asp.net标识在web API中设置令牌服务的操作如下所示
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// Note: Remove the following line before you deploy to production:
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
现在您可以使用jquery将用户名和密码发布到授权服务器并获取访问令牌
var loginData = {
grant_type: 'password',
username: self.loginEmail(),
password: self.loginPassword()
};
$.ajax({
type: 'POST',
url: '/Token',
data: loginData
}).done(function (data) {
self.user(data.userName);
// Cache the access token in session storage.
sessionStorage.setItem(tokenKey, data.access_token);
}).fail(showError);
然后,您可以在对web API的后续调用中使用存储在会话存储中的访问令牌
var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
$.ajax({
type: 'GET',
url: '/api/values',
headers: headers
}).done(function (data) {
self.result(data);
}).fail(showError);
您可以找到如何使用web API设置身份验证和授权的完整示例谢谢您的回答,它对我帮助很大。您的示例引用的是Web API 2.2,而不是ASP.NET 5引入的版本,但经过一些额外的研究后,我发现这篇文章:我能够在代码中采用这种方法,尽管在令牌请求期间,我仍然无法将密码验证与管理用户的身份框架连接起来(我目前不确定如何检查给定的用户名和密码是否属于现有用户)