1

I want to use AuthorizeAttribute for my Web API methods. But when user is not authorized method returns Login-View instead simple 401-status-code.

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{           
    // Another code.
    services.AddDefaultIdentity<User>(opt => {})
    .AddEntityFrameworkStores<MyDbContext>();
    // Another code.
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Another code.
    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "api/{controller}/{action=Index}/{id?}");
    });

    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "ClientApp";

        if (env.IsDevelopment())
        {
            spa.UseReactDevelopmentServer(npmScript: "start");
        }
    });
    // Another code.
}

SimpleController.cs:

[Route("api/[controller]")]
public class SimpleController : Controller
{
    [Authorize]
    [HttpGet("{id}")]
    public int Index(int Id)
    {
        return Id;
    }
}

In ASP.NET MVC 5 we have both AuthorizeAttribute:

  1. System.Web.Http.AuthorizeAttribute - which is used for the web API.
  2. System.Web.Mvc.AuthorizeAttribute - which is used for controllers with views.

But ASP.NET Core 2.0 has only one kind of attribute - for controllers with views. What do I need to do to get status-codes (401, 403) instead views?

5
  • Are you using forms authentication? Forms authentication will turn a 401 into a redirect to the login page. Commented Mar 15, 2019 at 20:57
  • @Amy Yes, I use forms authentication Commented Mar 15, 2019 at 21:01
  • 2
    That's your issue then. Don't use forms authentication with web api. Switch to cookie auth. See stackoverflow.com/questions/34880817/… Commented Mar 15, 2019 at 21:03
  • Is your whole project is api? Do you need to return 401/403 all over the project, right? Commented Mar 15, 2019 at 21:22
  • @Alexander Yes, I use ASP.NET + SPA (React) and therefore I need to return 401/403 all over the project. Commented Mar 15, 2019 at 21:25

1 Answer 1

4

ASP.NET Core Identity uses cookie authentication and therefore you can override CookieAuthenticationOptions.Events to make it work as you need. Identity provides ConfigureApplicationCookie configuration method for this.

services.ConfigureApplicationCookie(options =>
{
    //this event is called when user is unauthorized and is redirected to login page
    options.Events.OnRedirectToLogin = context =>
    {
        context.Response.StatusCode = 401;

        return Task.CompletedTask;
    };
});
Sign up to request clarification or add additional context in comments.

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.