2016-03-10 43 views
0

我目前正在学习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请求还是有一个更基本的问题在身份框架如何处理我不知道的用户授权?

在此先感谢您的答案!

回答

0

在web-API中使用安全性的推荐方法是将OAuth2与承载令牌一起使用。

您的设置的问题在于您尝试将表单身份验证与基于标记的身份验证相结合。

要在web-API中使用承载令牌,您需要在您的web-API中设置令牌服务(也称为STS或授权服务器)或使用某些外部令牌服务(如Google或Facebook)。

在web-API中设置令牌服务的步骤如下:使用asp.net标识。

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); 

你可以找到here

+0

谢谢您的回答如何设置身份验证和授权网络的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