4

The below portion of my startup.cs shows that I am using cookies based authentication. The option for "LoginPath" is utilized when an unauthenticated user tries to hit a resource that is protected. The problem is that this is done via HTTP. I want the resultant response/redirect to the login page to be HTTPS.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IConfiguration>(Configuration);
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/login";
                ....

I tried to hard code the LoginPath so that it would be forced to go through an HTTPS path, but I found that that option must be a relative path.

There is a downstream process (server/load balancer/something) which I have no power or viewership of that does a redirect to HTTPS, but this is not before the HTTP response occurs. I don't want that downstream process to have to handle the HTTP request. I would prefer this were handled in the application.

DutchMess
  • 101
  • 5
  • In your configure method, have you tried adding app.UseHttpsRedirection()? – Nik P May 14 '20 at 23:38
  • @NikP I tried that and it lead to a redirect loop. I will look into if there is a way to handle this loop so this solution can be fully vetted. – DutchMess May 15 '20 at 13:31

1 Answers1

6

I had previously looked at and glossed over the following answer, but it appears to work for my needs: ASP.NET Core CookieAuthenticationOptions.LoginPath on different domain

My final, modified (several options removed) solution within configure services in startup.cs:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.LoginPath = "/Login";
                    options.Events = new CookieAuthenticationEvents()
                    {
                        OnRedirectToLogin = (context) =>
                        {
                            context.HttpContext.Response.Redirect(context.RedirectUri.Replace("http://", "https://"));
                            return Task.CompletedTask;
                        }
                    };
                });

You would need to add a using to startup.cs for System.Threading.Tasks if you don't already have it.

DutchMess
  • 101
  • 5