2

在我使用代码的所有教程中

 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);
                    }
                };
            });

需要使用状态码 401 创建重定向,但因为我使用 ASP.NET 身份,所以我总是自动重定向到帐户/登录页面。

有人可以帮助我并告诉我如何不被重定向到帐户/登录并只返回状态 401。如果我使用任何其他状态(如 403 工作正常但 401 我可以返回)。谢谢。

4

1 回答 1

1

对此的修复是将其添加到身份提供者,而不是作为其自己的身份验证步骤。

所以:

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

而是将您的 cookie 设置添加到身份配置中:

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;
            }
        };
    });
于 2017-04-28T15:55:20.997 回答