C# .Net core 2.2未将302的状态代码更新为401。OnRedirectToLogin事件未触发

C# .Net core 2.2未将302的状态代码更新为401。OnRedirectToLogin事件未触发,c#,asp.net-core,.net-core,asp.net-core-mvc,identityserver4,C#,Asp.net Core,.net Core,Asp.net Core Mvc,Identityserver4,我正在使用identityserver4&我有以下startup.cs文件 当302状态代码存在时,我需要返回状态代码401。但似乎OnRedirectToLogin事件根本没有触发(调试点在事件中没有命中) 这段代码中有什么错误或遗漏了什么。我正在使用.NETCore2.2.1 它已成功编译并正在运行。但响应状态没有改变 using Clients; using IdentityModel; using IdentityModel.AspNetCore; using Microsoft.Asp

我正在使用identityserver4&我有以下startup.cs文件

当302状态代码存在时,我需要返回状态代码401。但似乎OnRedirectToLogin事件根本没有触发(调试点在事件中没有命中)

这段代码中有什么错误或遗漏了什么。我正在使用.NETCore2.2.1

它已成功编译并正在运行。但响应状态没有改变

using Clients;
using IdentityModel;
using IdentityModel.AspNetCore;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Threading.Tasks;
using VueCliMiddleware;

namespace sampleapp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(o =>
            {
                var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
                o.Filters.Add(new AuthorizeFilter(policy));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            #region Source: https://github.com/IdentityServer/IdentityServer4.Samples/blob/master/Clients/src/MvcHybridAutomaticRefresh/Startup.cs

            services.AddAuthentication(options =>
             {
                 options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                 options.DefaultChallengeScheme = "oidc";
             })
             .AddCookie(options =>
             {
                 options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
                 options.Cookie.Name = "mvchybridautorefresh";

                 //*****Following is not working. *****
                 //*****Following is not working. *****
                 //*****Following is not working. *****
                 options.Events.OnRedirectToLogin = context =>
                 {
                     if (IsAjaxRequest(context.Request))
                     {
                         context.Response.Headers["Location"] = context.RedirectUri;
                         context.Response.StatusCode = 401;
                     }
                     else
                     {
                         context.Response.Redirect(context.RedirectUri);
                     }
                     return Task.CompletedTask;
                 };
                 //*****Above is not working. *****
                 //*****Above is not working. *****
                 //*****Above is not working. *****
             })
             .AddAutomaticTokenManagement()
             .AddOpenIdConnect("oidc", options =>
             {
                 options.Authority = Constants.Authority;
                 options.RequireHttpsMetadata = false;

                 options.ClientSecret = "secret";
                 options.ClientId = "mvc.hybrid.autorefresh";

                 options.ResponseType = "code id_token";

                 options.Scope.Clear();
                 options.Scope.Add("openid");
                 options.Scope.Add("profile");
                 options.Scope.Add("email");
                 options.Scope.Add("api1");
                 options.Scope.Add("offline_access");

                 options.ClaimActions.MapAllExcept("iss", "nbf", "exp", "aud", "nonce", "iat", "c_hash");

                 options.GetClaimsFromUserInfoEndpoint = true;
                 options.SaveTokens = true;

                 options.TokenValidationParameters = new TokenValidationParameters
                 {
                     NameClaimType = JwtClaimTypes.Name,
                     RoleClaimType = JwtClaimTypes.Role,
                 };

             });

            #endregion

        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

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

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

                if (env.IsDevelopment())
                {
                    spa.Options.StartupTimeout = new TimeSpan(0, 0, 360);
                    spa.UseVueCli(npmScript: "serve", port: 8080);
                }
            });
        }

        private static bool IsAjaxRequest(HttpRequest request)
        {
            return string.Equals(request.Query["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal) ||
                string.Equals(request.Headers["X-Requested-With"], "XMLHttpRequest", StringComparison.Ordinal);
        }

    }
}

ASP.Net核心团队表示,如果使用oidc,将不会触发此事件

但我使用这个oidc进行cookieauthentication。所以我认为它应该(功能请求?)启动

没有标记为公认的答案,因为有人可能对此有意见

试试这个

options.Events.OnRedirectToAccessDenied = context =>
                    {
                        context.Response.StatusCode = 401;
                        return Task.CompletedTask;
                    };

我正在使用identityserver。所以根据我提供的答案。"". 但它仍然没有改变响应状态,调试点也没有到达那里。
options.Events.OnRedirectToAccessDenied = context =>
                    {
                        context.Response.StatusCode = 401;
                        return Task.CompletedTask;
                    };