1

I am having a problem calling a Web Api method when user is authenticated.

The fact is that when I call a Web Api method when user is authenticated, it is not recorgnized.

Formerly, I had problem with Logout method in AccountController. I solved it by using AllowAnonymous attribute.

However, now I am facing the same problem with ChangePassword method. I cannot add AllowAnonymous attribute in this case because when I do that I cannot retrieve the logged in user Id.

If I don't add AllowAnonymous attribute, system throws a forbidden error.

I am stuck here.... how can I solve it?

For instance, this is ChangePassword method in AccountController:

    // 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

jstuardo
  • 3,901
  • 14
  • 61
  • 136
  • Do you use dotnet core? Could you share the registration? Maybe checkout [Question 34306891](https://stackoverflow.com/questions/34306891/restrict-route-to-controller-namespace-in-asp-net-core) and [Filters in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.1) – Horace P. Greeley Dec 03 '18 at 21:42
  • Do you mean me to update the question to show you the controller action added by Visual Studio for registering a user? – jstuardo Dec 03 '18 at 22:32

1 Answers1

0

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

jstuardo
  • 3,901
  • 14
  • 61
  • 136