amc*_*dnl 26 asp.net asp.net-mvc-4 asp.net-web-api angularjs owin
我正在.NET Web应用程序中实现Web API 2服务体系结构.消费请求的客户端是纯javascript,没有mvc/asp.net.我正在使用OWIN尝试根据本文使用Web API示例进行OWIN Bearer Token身份验证来启用令牌身份验证.在获得授权后,我似乎遗漏了认证步骤.
我的登录信息如下:
[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);
}
Run Code Online (Sandbox Code Playgroud)
它回来了
{
accessToken: "TsJW9rh1ZgU9CjVWZd_3a855Gmjy6vbkit4yQ8EcBNU1-pSzNA_-_iLuKP3Uw88rSUmjQ7HotkLc78ADh3UHA3o7zd2Ne2PZilG4t3KdldjjO41GEQubG2NsM3ZBHW7uZI8VMDSGEce8rYuqj1XQbZzVv90zjOs4nFngCHHeN3PowR6cDUd8yr3VBLdZnXOYjiiuCF3_XlHGgrxUogkBSQ",
userName: "a@a.com"
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试Bearer在AngularJS中的进一步请求中设置HTTP标头,如:
$http.defaults.headers.common.Bearer = response.accessToken;
Run Code Online (Sandbox Code Playgroud)
到这样的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)
};
}
Run Code Online (Sandbox Code Playgroud)
但无论我做什么,这项服务都是"未经授权的".我在这里错过了什么吗?
amc*_*dnl 27
通过使用Bearer + token设置标题'Authorization'来解决,例如:
$http.defaults.headers.common["Authorization"] = 'Bearer ' + token.accessToken;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32886 次 |
| 最近记录: |