.NET core identity with SPA - return error code instead of redirect.

ASP.NET core

With ASP.NET core identity model - the default behavior when an access is denied or the user is not authenticated - would be to redirect to user to some predefined page.

With a single page application we expect to catch HTTP status codes and handle them directly.

To do so, we need to configure cookie events:

builder.Services.ConfigureApplicationCookie((options) =>
{
    options.Events.OnRedirectToAccessDenied += (context) =>
    {
        context.Response.StatusCode = 403;
        return Task.FromResult(0);
    };

    options.Events.OnRedirectToLogin += (context) =>
    {
        context.Response.StatusCode = 401;
        return Task.FromResult(0);
    };
});

Post a Comment

Previous Post Next Post