0

I've got a WebApi endpoint with an [Authorized] attribute. I did not configure any additional policies or anything.

[Authorized]
[Route("foo")]
public async Task<IActionResult> Foo(FooModel model) 
{ 
    // .......
}

When I try to hit this endpoint and I'm not authenticated I'll get a 404 response w/o content.

What I want to get: A customized response type with a 401 statuscode. How can I do that?

1

2 Answers 2

2

You can add following code in your Startup Class:

services.ConfigureApplicationCookie(options =>
        {
            options.Events.OnRedirectToLogin = context =>
            {
                context.Response.StatusCode = 401;
                return Task.CompletedTask;
            };
        });

Your action:

[Authorize]
public async Task<IActionResult> Foo(FooModel model) 
{ 
// ...
}

By the way,this will cause you can't redirect to your Login page, you can set it only works for api, like the following:

 services.ConfigureApplicationCookie(options =>
        {
            options.Events.OnRedirectToLogin = context =>
            {
                if (context.Request.Path.StartsWithSegments("/api")
                    && context.Response.StatusCode == StatusCodes.Status200OK)
                {
                    context.Response.Clear();
                    context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    return Task.CompletedTask;
                }
                context.Response.Redirect(context.RedirectUri);
                return Task.CompletedTask;
            };
        });
Sign up to request clarification or add additional context in comments.

1 Comment

If it doesn't work,please share your startup class.
0

Try using [Route] to make sure you are calling the function correctly

[Authorized]
[Route("Foo")]
public async Task<IActionResult> Foo(FooModel model) 
{ 

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.