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

我在我的.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 == "[email protected]" && 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: "[email protected]"
}

然后我尝试设置HTTP头承载在AngularJS进一步的请求喜欢:

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

到类似API的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)
        };
    }

但无论我做什么这项服务是“未经授权”。我在这里缺少什么?

解决方法

通过使用承载标记设置标题’授权’来解决:
$http.defaults.headers.common["Authorization"] = 'Bearer ' + token.accessToken;

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....