mvc6 unauthorized results in redirect instead

白昼怎懂夜的黑 提交于 2019-12-03 06:34:50

The solution is not to configure CookieAuthenticationOptions directly, but do it via IdentityOptions like this:

        services.Configure<IdentityOptions>(o =>
        {
            o.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = ctx =>
                {
                    if (ctx.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
                    {
                        return Task.FromResult<object>(null);
                    }
                    ctx.Response.Redirect(ctx.RedirectUri);
                    return Task.FromResult<object>(null);
                }
            };
        });

Taken from here ( Shawn Wildermuth --> ASP.NET 5 Identity and REST APIs --> Comment of "Mehdi Hanafi") and tested the API with Postman

config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
{
    OnRedirectToLogin = ctx =>
    {
        if (ctx.Request.Path.StartsWithSegments("/api") &&
        ctx.Response.StatusCode == 200)
        {
            ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            return Task.FromResult<object>(null);
        }
        else
        {
            ctx.Response.Redirect(ctx.RedirectUri);
            return Task.FromResult<object>(null);
        }
    }
};

from Identity 2.0, you'd need to add:

using Microsoft.AspNetCore.Authentication.Cookies;

and in ConfigureServices:

services.ConfigureApplicationCookie(options =>
{
    options.Events = new CookieAuthenticationEvents
    {
        OnRedirectToLogin = (x =>
        {
            if (x.Request.Path.StartsWithSegments("/api") && x.Response.StatusCode == 200)
                x.Response.StatusCode = 401;

            return Task.CompletedTask;
        }),
        OnRedirectToAccessDenied = (x =>
        {
            if (x.Request.Path.StartsWithSegments("/api") && x.Response.StatusCode == 200)
                x.Response.StatusCode = 403;

            return Task.CompletedTask;
        })
    };
});

the segments check should of course be adjusted to your routes.

Edward Brey

If you have some pages for which the redirect is desired and other URLs that should not have a redirect, see this question for a solution that uses the default redirect logic only for non-API URLs:

Suppress redirect on API URLs in ASP.NET Core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!