[英]Calling a Web Api method when user is authenticated
I am having a problem calling a Web Api method when user is authenticated. 验证用户身份时,我在调用Web Api方法时遇到问题。
The fact is that when I call a Web Api method when user is authenticated, it is not recorgnized. 事实是,当我通过用户身份验证时调用Web Api方法时,它不会重新组织。
Formerly, I had problem with Logout method in AccountController. 以前,我在AccountController中有Logout方法的问题。 I solved it by using AllowAnonymous attribute. 我通过使用AllowAnonymous属性解决了它。
However, now I am facing the same problem with ChangePassword method. 但是,现在我面临着ChangePassword方法的相同问题。 I cannot add AllowAnonymous attribute in this case because when I do that I cannot retrieve the logged in user Id. 在这种情况下,我无法添加AllowAnonymous属性,因为当我这样做时,我无法检索已登录的用户ID。
If I don't add AllowAnonymous attribute, system throws a forbidden error. 如果我不添加AllowAnonymous属性,系统将抛出一个禁止的错误。
I am stuck here.... how can I solve it? 我被困在这里...如何解决?
For instance, this is ChangePassword method in AccountController: 例如,这是AccountController中的ChangePassword方法:
// POST api/Account/ChangePassword
[Route("ChangePassword")]
public async Task<IHttpActionResult> ChangePassword(ChangePasswordBindingModel model)
{
if (!ModelState.IsValid)
{
// return BadRequest(ModelState);
return Json(GetModelErrorMessages());
}
try
{
IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword,
model.NewPassword);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
}
catch(Exception ex)
{
}
return Ok();
}
Thanks Jaime 谢谢海梅
Problem was due because i was not sending a bearer token with the request. 问题是由于我没有随请求发送承载令牌。
var tokenKey = 'accessToken';
var token = sessionStorage.getItem(tokenKey);
var headers = {};
if (token) {
headers.Authorization = 'Bearer ' + token;
}
$.ajax({
type: 'POST',
url: "/api/Account/ChangePassword",
data: JSON.stringify(data),
headers: headers,
contentType: 'application/json; charset=utf-8'
})
Now it works. 现在可以了。
Regards 问候
Jaime 海梅
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.