Azure AD Authentication seems to be skipped in my ASP.Net Core 2.2 application

507 Views Asked by At

I have an empty ASP.Net Core application and I'd like to have Azure AD authentication invoked. However my "milldeware" seems always ignore authentication. Please help me to figure out the root cause. Thank you. My appliaction is in .Net Core 2.2

Below is my startup.cs

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

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("AzureAD", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(AzureADDefaults.AuthenticationScheme‌​)
                    .RequireAuthenticatedUser().Build());
            });

            services.AddMvc();

            services.AddRouting();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();

            app.UseRouter(routes =>
            {
                routes.MapGet(string.Empty, HomeMiddleware);
                routes.MapGet("test", TestMiddleware);
            });
        }

Below are some middlewares I'd like to routes.

        [Authorize]
        private Task HomeMiddleware(HttpContext context)
        {
            return context.Response.WriteAsync($"control, User: {context.User.Identity.Name}");

        }

        [Authorize]
        private Task TestMiddleware(HttpContext context)
        {
            return Task.Run(() =>
            {
                var writer = new HttpResponseStreamWriter(context.Response.Body, Encoding.UTF8);
                writer.Write("test");
                writer.Flush();
                writer.Write("another test");
                writer.Flush();
            });
        }
    }

Seems [Authorize] doesn't work for my 'middleware'. the context.User.Identity.Name returns nothing to me and it doesn't redirect me to AzureAD authentication page.

1

There are 1 best solutions below

4
Pablo Recalde On

Update: net core 2.2 My bad.

I'm not sure the authorizeattribute works out of controllers. But I'd give it a try specifying the name of the policy like:

[Authorize("AzureAD")]

If that works but you don't want to specify the policy every time, I've seen in this link https://learn.microsoft.com/es-es/aspnet/core/security/authorization/secure-data?view=aspnetcore-2.2 there should be a FallbackPolicy property like the DefaultPolicy in 3.1:

services.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});

This is for 3.1.

First, you wan't to setup a default policy not to create just a policy. For that use

 auth.AddDefaultPolicy(builder => builder
     .AddAuthenticationSchemes(AzureADDefaults.AuthenticationScheme‌​)
     .RequireAuthenticatedUser().Build());

Second, you want to add the Authorization middleware, not only the authentication one.

 app.UseAuthentication();

 app.UseAuthorization();

 app.UseRouter(routes =>
 ...

Without this middleware Authorize attributes have no effect afaik

You can also leave the policy as it is and

A) use it on the app.UseAuthorization() call, I belive there's a overload to choose the default policy name there.

B) leave it being a named not default policy and use [Authorize("<policyName>")] on your endpoints.