Search code examples
authenticationproxyazure-active-directoryasp.net-core-mvcmicrosoft-identity-web

asp.net core 3.1 azure ad SSO authentication behind corporate proxy


I am trying to run an asp.net core 3.1 mvc web app that is running on a debian 10 container hosted on RHEL 7. The app is authenticating through Azure Ad OIDC SSO. the app must connect to Azure AD through a corporate proxy. I am trying to set up the proxy in asp.net core so that only the authentication traffic is going through the proxy. My startup file looks as follows:

using AutoMapper;
using CMM_MVP.Factories;
using CMM_MVP.Models;
using CMM_MVP.Services;
using CMM_MVP.Utils;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.UI;
using Microsoft.IdentityModel.Logging;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Net.Http;

namespace CMM_MVP
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(typeof(Startup));
            services.AddCors();
            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)   
                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));

            IdentityModelEventSource.ShowPII = true;

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });

            services.AddRazorPages().AddMicrosoftIdentityUI();


            //allow the HTTP Context object to be passed as a service to the controllers.
            services.AddHttpContextAccessor();

            services.AddSingleton<ISqlServerConnectionUtil, SqlServerConnectionUtil>();
            services.AddSingleton<IRepository<CustomerModel>, MockCustomersRepository>();
            services.AddScoped<ICustomerService, CustomerService>();
            services.AddSingleton<IUserService, UserService>();
            services.AddScoped<ICaseService, CaseService>();
            services.AddScoped<IViewCaseService, ViewCaseService>();
            services.AddScoped(typeof(IModelFactory<>), typeof(ModelFactory<>));

            services.AddDataProtection()
                .SetApplicationName("xxx")
                .PersistKeysToFileSystem(new System.IO.DirectoryInfo(@"/var/dpkeys/"));

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                IdentityModelEventSource.ShowPII = true;
            }
            else {
                app.UseHsts();
            }
            // Add support for sessions before using routing 
            //app.UseSession();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCors(builder =>
            {
                builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            });

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

I have seen that other threads exist using OpenIDConnect : Authenticate with Azure AD using .Net Core 3.00 from behind Corporate Proxy However since then Microsoft has introduced and recommended Microsoft.Identity.Web for Azure AD OIDC authentication which I am using instead. I have found another colleague that used the successfully working following setup (starts after .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd")); ):

        var aadProxy = new WebProxy()
        {
            Address = new Uri("http://address:port"),
            UseDefaultCredentials = true
            
        };

        IdentityModelEventSource.ShowPII = true;

        services.AddHttpClient("proxiedClient")
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
            {
                UseProxy = true,
                Proxy = aadProxy,
                PreAuthenticate = true
            });
        services.Configure<AadIssuerValidatorOptions>(options => { options.HttpClientName = "proxiedClient"; });

He also uses the following code, which does not apply to me as I am not setting up JwtTokens:

services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
        {
            options.TokenValidationParameters.RoleClaimType = "roles";
            options.BackchannelHttpHandler = new HttpClientHandler()
            {
                UseProxy = true,
                Proxy = aadProxy,
                PreAuthenticate = true,
            };
        });

I understood that the "BackchannelHttpHandler" is what handles the metadta from Azure AD. I have searched for ways to set the BackchannelHttpHandler for my use-case but could not find any.

It looks to me that setting up the BackchannelHttpHandler is the only thing i am missing atm but I do not know for sure?

Also I do not know how to configure it?


Solution

  • I have got this working now for few days without any probs. To answer my 2 questions:

    1. It looks to me that setting up the BackchannelHttpHandler is the only thing i am missing atm but I do not know for sure?

    Answer: BackchannelHttpHandler was indeed the only thing I was missing.

    1. Also I do not know how to configure it?

    Answer: using the options pattern: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1 the BackchannelHttpHandler property can be configured : https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.openidconnect.openidconnectoptions?view=aspnetcore-3.1 right after the line : services.Configure(options => { options.HttpClientName = "proxiedClient"; });

    in the question. the code that needs to be added after the line above to configure the BackchannelHttpHandler property in OpenIDConnect options is as follows:

        services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, 
    options =>
        {
            options.BackchannelHttpHandler = new HttpClientHandler()
            {
                UseProxy = true,
                Proxy = aadProxy,
                PreAuthenticate = true,
            };
        });
    

    That's all. SSO through Azure AD OpenID Connect is working successfully now.