I'm using Azure AD with OpenIDConnect and I'd like to use bearer tokens to authorize MVC controller actions that return json and cookies to authorize actions that return views, so I added the JwtBearerAuthentication middleware to my startup file and set AutomaticAuthenticate to false for the Cookie, OpenIdConnect, and JwtBearer middleware per the Limiting identity by scheme article.
So the problem is that the Cookie middleware doesn't work at all when I use [Authorize(ActiveAuthenticationSchemes ="cookie")] ,and I just end up being redirected to the /Account/AccessDenied page every time instead of the Azure AD login screen.
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); options.Filters.Add(new RequireHttpsAttribute()); }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); //app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseDeveloperExceptionPage(); app.UseStaticFiles(); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "cookie", AutomaticAuthenticate = false }); app.UseJwtBearerAuthentication(new JwtBearerOptions { AuthenticationScheme = "bearer", Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], Audience = Configuration["Authentication:AzureAd:ClientId"], AutomaticAuthenticate = false }); app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions { ClientId = Configuration["Authentication:AzureAd:ClientId"], Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"], CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"], AuthenticationScheme = "oidc", SignInScheme = "cookie", AutomaticAuthenticate = false, }); app.UseStatusCodePages(); app.UseMvc(routes => { routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public class HomeController : Controller { [Authorize(ActiveAuthenticationSchemes = "cookie")] public IActionResult Index() { return View(); } public IActionResult Error() { return View(); } }