gpt4 book ai didi

c# - .Net 核心 2.2 未将 302 的状态代码更新为 401。OnRedirectToLogin 事件未触发

转载 作者:行者123 更新时间:2023-12-05 07:26:01 26 4
gpt4 key购买 nike

我正在使用 identityserver4 并且我有以下 startup.cs 文件。

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

这段代码有什么问题或我遗漏了什么。我正在使用 .net 核心 2.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);
}

}
}

最佳答案

    .AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
options.Cookie.Name = "mvchybridautorefresh";

options.LoginPath = new PathString("/Account/Login"); //please provide your login/logout path
options.LogoutPath = new PathString("/Account/Logout");

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

})

关于c# - .Net 核心 2.2 未将 302 的状态代码更新为 401。OnRedirectToLogin 事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54560707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com