一尘不染

.NET Web API 2 OWIN承载令牌认证

angularjs

我正在.NET Web应用程序中实现Web API 2服务体系结构。使用请求的客户端是纯JavaScript,没有mvc /
asp.net。我正在使用OWIN根据本文尝试启用令牌身份验证,并使用Web API
Sample进行OWIN承载令牌身份验证
。授权后,我似乎在身份验证步骤中缺少某些内容。

我的登录名如下:

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

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


阅读 255

收藏
2020-07-04

共1个答案

一尘不染

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

$http.defaults.headers.common["Authorization"] = 'Bearer ' + token.accessToken;
2020-07-04