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 == "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) }; }但無論我做什麼,這項服務都是“未經授權的”。我在這裡錯過了什麼嗎?
通過使用 Bearer + 令牌設置標題“授權”來解決,例如:
$http.defaults.headers.common["Authorization"] = 'Bearer ' + token.accessToken;