.NET Web API 2 OWIN承载令牌认证
我在.NET Web应用程序中实现了Web API 2服务体系结构。 消费请求的客户端是纯javascript,没有mvc / asp.net。 我正在使用OWIN尝试启用本文的OWIN持票人令牌身份验证和Web API示例的令牌身份验证。 在授权后,我似乎错过了身份验证步骤。
我的登录如下所示:
[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"
}
然后我尝试在AngularJS的更多请求中设置HTTP标头Bearer
,如:
$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)
};
}
但无论我做什么这项服务是'未经授权'。 我在这里错过了什么吗?
通过使用持票人+标记设置标题'授权'解决,如:
$http.defaults.headers.common["Authorization"] = 'Bearer ' + token.accessToken;
您可以使用角度应用程序模块对其进行配置。 因此授权令牌将被设置为每个http请求的标头。
var app = angular.module("app", ["ngRoute"]);
app.run(function ($http) {
$http.defaults.headers.common.Authorization = 'Bearer ' + token.accessToken;
});
链接地址: http://www.djcxy.com/p/22441.html