首页 文章

尝试将OIDC OnRedirectToIdentityProvider从302更改为401

提问于
浏览
1

我们正在使用带有自定义登录页面的Identity Server 4 . 我们一直在测试cookie过期或手动修改令牌(硬化的一部分)时会发生什么 .

应用程序想要将我们重定向到https://localhost:44349/signin-oidc,并返回302重定向,但/ signin-oidc并不想抛出401并将它们重定向到/ home .

我已经找到了可以捕捉事件的地方

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错误,没有任何办法向用户报告发生了什么 .

1 回答

  • 3

    发现这个小宝石here

    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() .

相关问题