Enable both Windows authentication and Anonymous authentication in an ASP.NET Core app

后端 未结 4 1107
日久生厌
日久生厌 2020-12-25 14:34

I know that this has been asked many times before, but unfortunately not about ASP.NET Core web apps, just the classic ASP.NET web apps. All the answers i\'ve found on the i

4条回答
  •  既然无缘
    2020-12-25 15:12

    In case anyone wonders, I modified @Alexei's answer to use Attributes rather than request path in Netcore 3.X

    First create the class and get the endpoints metadata

    public class NtlmAndAnonymousSetupMiddleware
    {
        private readonly RequestDelegate next;
    
        public NtlmAndAnonymousSetupMiddleware(RequestDelegate next)
        {
            this.next = next;
        }
    
        public async Task Invoke(HttpContext context)
        {
    
            if (context.User.Identity.IsAuthenticated || HasAnonymousAttribute(context))
            {
                await next(context);
                return;
            }
    
            await context.ChallengeAsync("Windows");
        }
    
        private bool HasAnonymousAttribute(HttpContext context)
        {
            var endpoint = context.GetEndpoint();
            var retVal = (endpoint?.Metadata?.GetMetadata() != null);
    
            return retVal;
        }
    }
    

    Then modify public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseMiddleware();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
            });
    

提交回复
热议问题