Trying to change OIDC OnRedirectToIdentityProvider from 302 to 401

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

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

But this doesn't seem to work and we simply throw a 302 error without any way to report back to user what happened.

1 answer

  • answered 2018-01-11 19:40 MADC0D3R

    Found this little gem here

    OnRedirectToIdentityProvider = ctx =>
    if (ctx.Request.Path.StartsWithSegments("/api"))
    if (ctx.Response.StatusCode == (int)HttpStatusCode.OK)
    ctx.Response.StatusCode = 401;
    return Task.CompletedTask;

    It does exactly what I need, which is to return a 401. The trick was in the HandleResponse().