0

I have a ASP.NET Core 3.1.8 Web Application uses ASP Identity. All is working OK, when user try to navigate to a page which requires authentication, the response redirects the user to the login page.

Recently I created some API controller:

[Route("api/[controller]/[action]")]
[ApiController]
[Produces("application/json")]
public class MyController : ControllerBase
{
    [HttpGet]
    [Authorize]
    public ActionResult<string> PingAuth(string message)
    {
        return Ok($"Pong: {message}");
    }

During testing I noticed, that in case I call it with no authentication the response is the redirect, instead of the 401 Unauthorized.

Question

Is there any way to explain the api controller to send [401: Unauthorized] instead of [302: Found]?

g.pickardou
  • 24,276
  • 25
  • 91
  • 195
  • You have configured only a single authorization policy (the default one), therefore all http requests will behave the same (i.e. will redirect) – Michael Shterenberg Oct 14 '20 at 07:21
  • 1
    Check this answer: https://stackoverflow.com/questions/32863080/how-to-remove-the-redirect-from-an-asp-net-core-webapi-and-return-http-401 – Michael Shterenberg Oct 14 '20 at 07:32
  • The question you referred is working with minor changes, I mean filtering which path `services.ConfigureApplicationCookie...` should return with 302 and which with 401. However I still do not understand what to do with "policies" (your first comment) – g.pickardou Oct 14 '20 at 09:06
  • Which kind of authentication are you using? Can you post the related configure code in the Startup.cs file? Here is a thread about [ASP.NET Core Web API unauthorized requests returns 302 redirect response instead of 401](https://stackoverflow.com/questions/30411296/asp-net-asp-net-core-web-api-unauthorized-requests-returns-302-redirect-respon), might be it can help you. – Zhi Lv Oct 15 '20 at 15:19

1 Answers1

0

Try to use Authorize attribute's property Policy and require authenticated users:

In Startup, ConfigureServices:

services.AddAuthorization(op=>{
            op.AddPolicy("AuthUsers", policy=>{
                policy.RequireAuthenticatedUser();
            });
        });

Then you can use [Authorize(Policy="AuthUsers")]

kavanka
  • 93
  • 7