Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postman request with ASP.NET Core API call is unauthorized

I just created an ASP.NET Core application and I am trying to test a Web API call that creates an item using the following controller method below. But I am following the instructions on this page (https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api) which uses Postman to test the method.

[HttpPost]
[Route("api/asset")]
public IActionResult Create([FromBody] Asset asset)
{
    if (!ModelState.IsValid)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return null;
    }
    AssetItems.Add(asset);
    return CreatedAtRoute("GetAsset", new { id = asset.Id }, asset);
}

But when I make the request using Postman, I get the error:

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers.

like image 960
Ray Avatar asked Oct 15 '25 07:10

Ray


1 Answers

Check to see if authentication/authorization filter has been added to request pipeline. Could have been added based on the project template you used when creating project.

If the controller has an [Authorize] attribute then removing it should allow requests through.

If however the Authorize filter was added globally then you may need to add an [AllowAnonymous] attribute on the action or controller to let requests through for that action or controller.

[HttpPost]
[AllowAnonymous]
[Route("api/asset")]
public IActionResult Create([FromBody] Asset asset) { ... }
like image 77
Nkosi Avatar answered Oct 17 '25 16:10

Nkosi