26

我正在我的 .NET Web 应用程序中实现 Web API 2 服务架构。使用请求的客户端是纯 javascript,没有 mvc/asp.net。我正在使用 OWIN 尝试按照本文OWIN Bearer Token Authentication with Web API Sample启用令牌身份验证。在授权后,我似乎在身份验证步骤中遗漏了一些东西。

我的登录看起来像:

    [HttpPost]
    [AllowAnonymous]
    [Route("api/account/login")]
    public HttpResponseMessage Login(LoginBindingModel login)
    {
        // todo: add auth
        if (login.UserName == "a@a.com" && login.Password == "a")
        {
            var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, login.UserName));

            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
            var currentUtc = new SystemClock().UtcNow;
            ticket.Properties.IssuedUtc = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));

            DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); 

            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ObjectContent<object>(new  
                { 
                    UserName = login.UserName,
                    AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket)
                }, Configuration.Formatters.JsonFormatter)
            };
        }

        return new HttpResponseMessage(HttpStatusCode.BadRequest);
    }

它返回

{
   accessToken: "TsJW9rh1ZgU9CjVWZd_3a855Gmjy6vbkit4yQ8EcBNU1-pSzNA_-_iLuKP3Uw88rSUmjQ7HotkLc78ADh3UHA3o7zd2Ne2PZilG4t3KdldjjO41GEQubG2NsM3ZBHW7uZI8VMDSGEce8rYuqj1XQbZzVv90zjOs4nFngCHHeN3PowR6cDUd8yr3VBLdZnXOYjiiuCF3_XlHGgrxUogkBSQ",
   userName: "a@a.com"
}

然后我尝试Bearer在 AngularJS 中为进一步的请求设置 HTTP 标头,例如:

$http.defaults.headers.common.Bearer = response.accessToken;

到一个 API,如:

    [HttpGet]
    [Route("api/account/profile")]
    [Authorize]
    public HttpResponseMessage Profile()
    {
        return new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ObjectContent<object>(new
            {
                UserName = User.Identity.Name
            }, Configuration.Formatters.JsonFormatter)
        };
    }

但无论我做什么,这项服务都是“未经授权的”。我在这里错过了什么吗?

4

2 回答 2

27

通过使用 Bearer + 令牌设置标题“授权”来解决,例如:

$http.defaults.headers.common["Authorization"] = 'Bearer ' + token.accessToken;
于 2013-11-04T15:04:31.493 回答
0

您可以使用 Angular 应用程序模块对其进行配置。因此,授权令牌将被设置为每个 http 请求的标头。

var app = angular.module("app", ["ngRoute"]);
app.run(function ($http) {

     $http.defaults.headers.common.Authorization = 'Bearer ' + token.accessToken;

});
于 2017-09-27T05:52:20.893 回答