maxisam maxisam - 9 days ago 5
ASP.NET (C#) Question

Asp.net Identity 3 return 403 Unauthorized request instead of redirect for WebAPI call

I used Asp.net Identity 3 within Asp.net core project (only compile against net451.)

Here is the question, when I call the WebAPI with [Authorize] tag, the system always return the login url instead of 401 for unauthorized call. I wonder how to make it return 401 ?

Answer

It turns out in startup.cs

services.AddIdentity<ApplicationUser, IdentityRole>()

change to the following code will take care this issue.

        services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToAccessDenied = context => {
                        context.Response.StatusCode = 403;
                        return Task.FromResult(0);
                    },
                    OnRedirectToLogin = context =>
                    {
                        context.Response.StatusCode = 401;
                        return Task.FromResult(0);
                    }
                };
                options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
            })