cookie 过期后如何 return 401 状态而不是 302 重定向?

How do I return a 401 status instead of a 302 redirect after cookie has expired?

我正在使用不带 Identity 和以下 Nuget 包的 cookie 身份验证:

<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.WsFederation" Version="2.0.3" />

我在我的 cookie 上设置了一个较短的超时时间,并希望我的 API 调用 return 一个 401 状态,而不是 cookie 过期时的 302 重定向。我的 ConfigureServices 如下所示:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IRestService, RestService>();

    services.AddDataProtection()
        .SetApplicationName("AspNetCookieShare")
        .PersistKeysToFileSystem(new DirectoryInfo(Configuration["DataProtectionKeyDirectory"]));

    services.AddAuthentication(sharedOptions =>
        {
            sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
        })
        .AddWsFederation(options =>
        {
            options.Wtrealm = Configuration["Wtrealm"];
            options.MetadataAddress = "http://example.com/metadata.xml";
            options.SkipUnrecognizedRequests = true;
            options.RequireHttpsMetadata = false;
            options.UseTokenLifetime = false;
        })
        .AddCookie(options =>
        {
            options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
            options.Cookie.Expiration = TimeSpan.FromSeconds(10);
            options.Cookie.Name = "AspNetShared";
            options.Cookie.Path = "/";

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

    services.AddMvc();
}

我正在使用 OnRedirectToLogin,但是,在 cookie 过期后我仍然收到 302 响应而不是 401:

我做错了什么?

我将 services.AddWsFederation() 更改为以下内容,它似乎可以正常工作:

.AddWsFederation(options =>
{
    options.Wtrealm = Configuration["Wtrealm"];
    options.MetadataAddress = "http://example.com/metadata.xml";
    options.SkipUnrecognizedRequests = true;
    options.RequireHttpsMetadata = false;
    options.UseTokenLifetime = false;
    options.Events.OnRedirectToIdentityProvider = context =>
    {
        context.Response.StatusCode = 401;
        context.HandleResponse();
        return Task.CompletedTask;
    };
})

已针对 TargetFramework = net6.0 进行测试

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        ...
        options.EventsType = typeof(CustomCookieAuthenticationEvents);
    });
builder.Services.AddSingleton<CustomCookieAuthenticationEvents>();
public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
{
    public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context)
    {
        context.Response.StatusCode = 401;
        return Task.CompletedTask;
    }

    public override Task RedirectToAccessDenied(RedirectContext<CookieAuthenticationOptions> context)
    {
        context.Response.StatusCode = 403;
        return Task.CompletedTask;
    }
}