我使用没有Identity的Cookie身份验证和以下Nuget包:
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.WsFederation" Version="2.0.3" />
我在我的Cookie上设置了一个短暂超时,并希望我的API调用在Cookie过期时返回401状态而不是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:
我做错了什么?
答案 0 :(得分:1)
我将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;
};
})