Andrej Matijevic
Andrej Matijevic

Reputation: 56

How to response status 401 on ASP.NET 5 ASP.NET Identity 3.0 RC1

In all tutorials that I use the code

 app.UseCookieAuthentication(ctx =>
            {
                ctx.AutomaticChallenge = true;
                ctx.Events = new CookieAuthenticationEvents()
                {
                    OnRedirectToLogin = context =>
                    {
                        context.Response.Headers["Location"] = context.RedirectUri;
                        context.Response.StatusCode = 401;
                        return Task.FromResult(0);
                    }
                };
            });

Would need to create redirect with status code 401 but because I use ASP.NET identity I'm always automatically redirect to Account/Login page.

Can some wan help me and tell me how to not be redirected to Account/Login and just return status 401. If I use any other status like 403 that is working perfectly but 401 I can return. Thanks.

Upvotes: 2

Views: 1199

Answers (1)

Keith
Keith

Reputation: 155652

This fix for this is to add it to the identity provider, rather than as its own authentication step.

So:

public void Configure(IApplicationBuilder app, ...) 
{
    ...
    app.UseIdentity();
    ...
    // Ignored, because identity does its own auth and is before it in the middleware
    app.UseCookieAuthentication(...):

Instead add your cookie settings to the identity config:

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Configure identity service
    services.AddIdentity<AppUser, AppRole>(options =>
    {
        // Set cookie options for that service
        var ctx = options.Cookies.ApplicationCookie;

        // Your code
        ctx.AutomaticChallenge = true;
        ctx.Events = new CookieAuthenticationEvents
        {
            OnRedirectToLogin = context =>
            {
                context.Response.Headers["Location"] = context.RedirectUri;
                context.Response.StatusCode =
                    (int) HttpStatusCode.Unauthorized; 
                return Task.CompletedTask;
            }
        };
    });

Upvotes: 1

Related Questions