boop
boop

Reputation: 7788

Customize Asp.NET Core Identity Unauthorized Response Type and Statuscode

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?

Upvotes: 0

Views: 504

Answers (2)

Yinqiu
Yinqiu

Reputation: 7190

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;
            };
        });

Upvotes: 2

Wowo Ot
Wowo Ot

Reputation: 1529

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

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

}

Upvotes: 0

Related Questions