How to configure UseCookieAuthentication behind a load balancer

I am configuring a .netcore application to use OIDC authentication (provided by IdentityServer).

I have included the following code in my StartUp

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "Cookies",
    AutomaticAuthenticate = true,
    ExpireTimeSpan = TimeSpan.FromMinutes(60)
});

JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    AuthenticationScheme = "oidc",
    SignInScheme = "Cookies",

    Authority = "https://myauthority",
    ClientId = "myclient",
    CallbackPath = "/",
    ResponseType = "id_token token",
    Scope = { "openid", "profile", "email" },
});

The application is hosted on AWS, in a docker running on ECS. It works for the application load balancer listening on https.

I found that since my application does not use HTTPS (because https ends with a load balancer), the OIDC middleware generates an invalid return URL when redirecting to the OIDC server - the URL that it creates starts with http: //.

The return URL is generated by the BuildRedirectUri method in the AuthenticationHandler base class. It just uses the protocol it received the request for, but cannot override it.

protected string BuildRedirectUri(string targetPath)
{
    return this.Request.Scheme + "://" + this.Request.Host + this.OriginalPathBase + targetPath;
}

, HTTP, ?

" " ? ?

+4
2

(, IIS Kestrel , ), X-Forwarded-For X-Forwarded-Proto HTTP-. , ​​ , . , , ForwardedHeaders Microsoft.AspNetCore.HttpOverrides. , :

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

.

+3

ForwarededHeaders . , - ( ASP.NET Core Docs).

Configure:

 var options = new ForwardedHeadersOptions
        {
            ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
        };
 options.KnownNetworks.Clear();
 options.KnownProxies.Clear();
 app.UseForwardedHeaders(options);

, , , https://leastprivilege.com/2017/10/09/new-in-identityserver4-v2-simplified-configuration-behind-load-balancers-or-reverse -/. ( ):

services.AddIdentityServer(options =>
            {
                ...
               options.PublicOrigin = "https://whatever.domain.com";
                ...
            })
+1

Source: https://habr.com/ru/post/1674260/


All Articles