c# - How do I get HttpContext to Authenticate User using OpenIDConnect? - Stack Overflow

admin2025-05-01  0

Previously developed was an application that had authentication with Microsoft identity providers via OpenIdConnect:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(options =>
                {
                    options.Instance = "/";
                    options.TenantId = TenantId;
                    options.ClientId = builder.Configuration.GetValue<string>("AzureADClientID");
                    options.ClientSecret = builder.Configuration.GetValue<string>("AzureADSecret");
                    options.CallbackPath = "/signin-oidc";
                    options.SaveTokens = true; // Ensure tokens are saved

                });

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<CustomAuthenticationMiddleware>();

Now, I am wanting to add a custom layer of middleware to this project. It should use HttPContext, extracting it's information to perform the custom MiddleWare logic. I have this custom middleware added to be included in my Program.cs file. Here is where the custom middleware begins execution:

        [Authorize]
        public async Task Invoke(HttpContext context)
        {

            bool authValid = false;
            authValid = await CheckIfUserAPIAuth(context);
            // bool authValid = true;
            if (authValid)
            {
                await _next.Invoke(context);
            }
            else
            {
                context.Response.StatusCode = 401; //Unauthorized
                return;
            }
        }

However, the context.User field is set to IsAuthenticated = false when this is invoked. Ideally, I would like the User information to be their system information, but I can also ultimately use the AzureAD information, such as AD-GUID, to continue with my custom logic. However, the current context looks like this:

Previously developed was an application that had authentication with Microsoft identity providers via OpenIdConnect:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(options =>
                {
                    options.Instance = "https://login.microsoftonline.com/";
                    options.TenantId = TenantId;
                    options.ClientId = builder.Configuration.GetValue<string>("AzureADClientID");
                    options.ClientSecret = builder.Configuration.GetValue<string>("AzureADSecret");
                    options.CallbackPath = "/signin-oidc";
                    options.SaveTokens = true; // Ensure tokens are saved

                });

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<CustomAuthenticationMiddleware>();

Now, I am wanting to add a custom layer of middleware to this project. It should use HttPContext, extracting it's information to perform the custom MiddleWare logic. I have this custom middleware added to be included in my Program.cs file. Here is where the custom middleware begins execution:

        [Authorize]
        public async Task Invoke(HttpContext context)
        {

            bool authValid = false;
            authValid = await CheckIfUserAPIAuth(context);
            // bool authValid = true;
            if (authValid)
            {
                await _next.Invoke(context);
            }
            else
            {
                context.Response.StatusCode = 401; //Unauthorized
                return;
            }
        }

However, the context.User field is set to IsAuthenticated = false when this is invoked. Ideally, I would like the User information to be their system information, but I can also ultimately use the AzureAD information, such as AD-GUID, to continue with my custom logic. However, the current context looks like this:

Share Improve this question edited Jan 2 at 19:25 zackychan97 asked Jan 2 at 15:00 zackychan97zackychan97 1562 silver badges11 bronze badges 7
  • 1 If you want top use your own auth you need to set the user in the context yourself. – Clemens Commented Jan 2 at 15:04
  • @Clemens Is that something typically done in Program.cs? I am looking at this example: learn.microsoft.com/en-us/aspnet/core/fundamentals/… (scroll down to USER section and code example) – zackychan97 Commented Jan 2 at 15:10
  • I think auth ist best not done individually. If you have to I personally think you could write Extension methods and apply them in programm.cs. But my advise holds: dont do auth one your own unless you know exactly what you are doing :-) – Clemens Commented Jan 2 at 15:15
  • @Clemens Okay. Are you aware of / do you know of built in functionality that will automatically inject HttPContext with the user's Windows credentials? You mentioned doing it oneself, but how does that look? You meant with Extension methods then? – zackychan97 Commented Jan 2 at 15:56
  • Register your middleware after Authentication and Authorization middleware. – sa-es-ir Commented Jan 2 at 17:09
 |  Show 2 more comments

1 Answer 1

Reset to default 1

If you try to use SignIn explicitly I think it should work, basically you're saying if the incoming token validated successfully then set the user into HttpContext.

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(options =>
                {
                    options.Instance = "https://login.microsoftonline.com/";
                    options.TenantId = TenantId;
                    options.ClientId = builder.Configuration.GetValue<string>("AzureADClientID");
                    options.ClientSecret = builder.Configuration.GetValue<string>("AzureADSecret");
                    options.CallbackPath = "/signin-oidc";
                    options.SaveTokens = true; // Ensure tokens are saved
                    options.Events.OnTokenValidated = async context =>
                    {
                        await context.HttpContext.SignInAsync(
                            OpenIdConnectDefaults.AuthenticationScheme, context.Principal);
                    };
                    
                    options.Events.OnAuthenticationFailed = context =>
                    {
                        // check the context.Exception or response
                        return Task.CompletedTask;
                    };

                });
转载请注明原文地址:http://anycun.com/QandA/1746110969a91819.html