Access to user credentials in ASP.NET Core middleware

Change AllowAnonymous

options.Authentication.AllowAnonymous = false;

If you have anonymous on, and you're not prompting for authentication then the browser isn't going to authenticate. Even if you do send creates asp.net isn't going to get them unless there's an Authenticate attribute on the controller/method or, if you're going the function route, you call signin.


If you would not want to set AllowAnonymous as false, you could try context.ChallengeAsync to authenticate the request based on Credential.

Here are the code:

        app.MapWhen(context => context.Request.Path.Equals("/sensitiveOperation") && context.Request.Method.Equals(HttpMethods.Put), subApp =>
        {
            subApp.Run(async (context) =>
            {
                var authService = context.RequestServices.GetRequiredService<IAuthorizationService>();

                if (!context.User.Identity.IsAuthenticated)
                {
                    //await context.ChallengeAsync("Windows"); //Option1
                    //await context.ChallengeAsync();  //Option2
                    await context.ChallengeAsync(HttpSysDefaults.AuthenticationScheme); //Option3
                }
                if (context.User.Identity.Name == "admin")
                {
                    await context.Response.WriteAsync("Performing sensitive operation.");
                    // .. Do Sensitive operation....
                }
            });
        });

Note, for this way, subApp.Run will run twice, first request is UnAuthenticated, and it will challenge the credentail, second request is Authenticated and context.User.Identity.Name will have value. This process is back-end, this would not be reflected in powershell.


I am using .NET Core 3.0 and in my custom middleware I was able to get the UserId with this code:

httpContext.User.Identity.IsAuthenticated 
    ? new Guid(httpContext.User.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).First().Value)
    : Guid.Empty