Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect in .NET Core OpenID Connect middleware?

I'm trying to handle a scenario when the OpenID Connect server I'm authenticating to returns a particular set of querystrings. When the condition matches, I want to essentially redirect the user to an "Access Denied" page. For whatever reason the commented line below containing the redirect never actually fires. Is there a better/different way to do what I'm after?

Here's how the OpenID Connect middleware is configured in Startup.cs:

services.Configure<OpenIdConnectOptions>(options => 
{

    // ...

    options.Events = new OpenIdConnectEvents
    {
        OnMessageReceived = context =>
        {
            if (context.HttpContext.Request.Query.ContainsKey("error"))
            {
                context.HandleResponse(); // <-- Fires
                context.Response.Redirect("/AccessDenied"); // <-- Redirect fires but user is not redirected
            }

            return Task.FromResult(0);
        }
    }
}

UPDATE: Got it working with the following tweaks:

options.Events = new OpenIdConnectEvents
{
    OnRemoteFailure = context =>
    {
        context.HandleResponse();
        context.Response.Redirect("AccessDenied?error=" + context.Failure.Message);

        return Task.FromResult(0);
    },
    // ...
};
like image 988
ianpoley Avatar asked Jul 05 '16 04:07

ianpoley


1 Answers

You should not to call HandleResponse() before redirect, as in this case you "tell" to stop processing request in HTTP Pipeline. Change to this:

        if (context.HttpContext.Request.Query.ContainsKey("error"))
        {
            context.Response.Redirect("/AccessDenied"); 
            context.HandleResponse(); 
        }
like image 77
Set Avatar answered Dec 23 '22 16:12

Set