试图将 OIDC OnRedirectToIdentityProvider 从 302 更改为 401 [英] Trying to change OIDC OnRedirectToIdentityProvider from 302 to 401
问题描述
我们正在使用带有自定义登录页面的 Identity Server 4.我们一直在测试当 cookie 过期或令牌被手动修改时会发生什么(硬化的一部分).
We are using Identity Server 4 with a custom login page. We've been testing what happens when the cookie expires or the token is manually modified (part of hardening).
应用程序想要将我们重定向到 https://localhost:44349/signin-oidc,并返回 302 重定向,但/signin-oidc 不存在.我们想抛出 401 并将它们重定向到/home.
The application wants to redirect us to https://localhost:44349/signin-oidc, and returns a 302 redirect, but /signin-oidc doesn't exist. We'd like to throw a 401 and redirect them to /home.
我找到了可以捕捉事件的地方
I've found where I can capture the events
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = context => {
var newRedirect = context.ProtocolMessage.RedirectUri.ToString().Replace("signin-oidc", "home");
var builder = new UriBuilder(newRedirect);
builder.Scheme = "https";
context.ProtocolMessage.RedirectUri = builder.ToString();
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Task.FromResult(0);
}
};
但这似乎不起作用,我们只是抛出 302 错误,而没有任何方式向用户报告发生的情况.
But this doesn't seem to work and we simply throw a 302 error without any way to report back to user what happened.
推荐答案
发现这个小宝石 这里
OnRedirectToIdentityProvider = ctx =>
{
if (ctx.Request.Path.StartsWithSegments("/api"))
{
if (ctx.Response.StatusCode == (int)HttpStatusCode.OK)
{
ctx.Response.StatusCode = 401;
}
ctx.HandleResponse();
}
return Task.CompletedTask;
}
它完全符合我的需要,即返回 401.诀窍在于 HandleResponse().
It does exactly what I need, which is to return a 401. The trick was in the HandleResponse().
这篇关于试图将 OIDC OnRedirectToIdentityProvider 从 302 更改为 401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!