gpt4 book ai didi

asp.net - .NET Web API 2 OWIN 承载 token 身份验证

转载 作者:行者123 更新时间:2023-12-02 18:27:23 29 4
gpt4 key购买 nike

我正在我的 .NET Web 应用程序中实现 Web API 2 服务架构。消费请求的客户端是纯 javascript,没有 mvc/asp.net。我正在使用 OWIN 尝试根据本文 OWIN Bearer Token Authentication with Web API Sample 启用 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);
}

返回

{
accessToken: "TsJW9rh1ZgU9CjVWZd_3a855Gmjy6vbkit4yQ8EcBNU1-pSzNA_-_iLuKP3Uw88rSUmjQ7HotkLc78ADh3UHA3o7zd2Ne2PZilG4t3KdldjjO41GEQubG2NsM3ZBHW7uZI8VMDSGEce8rYuqj1XQbZzVv90zjOs4nFngCHHeN3PowR6cDUd8yr3VBLdZnXOYjiiuCF3_XlHGgrxUogkBSQ",
userName: "a@a.com"
}

然后我尝试在 AngularJS 中的进一步请求中设置 HTTP header 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)
};
}

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

最佳答案

通过使用 Bearer + token 设置 header “Authorization”来解决,例如:

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

关于asp.net - .NET Web API 2 OWIN 承载 token 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19769422/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com