I'm trying to add Azure AD authentication to my ASP.NET 5 MVC 6 application and have followed this example on GitHub. Everything works fine if I put the recommended code in an action method:
Context.Response.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
However, if I try using the [Authorize]
attribute instead, I get an immediate empty 401 response.
How can I make [Authorize]
redirect properly to Azure AD?
My configuration is as follows:
public void ConfigureServices(IServiceCollection services) {
...
services.Configure<ExternalAuthenticationOptions>(options => {
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
...
app.UseCookieAuthentication(options => {
options.AutomaticAuthentication = true;
});
app.UseOpenIdConnectAuthentication(options => {
options.ClientId = Configuration.Get("AzureAd:ClientId");
options.Authority = String.Format(Configuration.Get("AzureAd:AadInstance"), Configuration.Get("AzureAd:Tenant"));
options.RedirectUri = "https://localhost:44300";
options.PostLogoutRedirectUri = Configuration.Get("AzureAd:PostLogoutRedirectUri");
options.Notifications = new OpenIdConnectAuthenticationNotifications {
AuthenticationFailed = OnAuthenticationFailed
};
});
...
}
To automatically redirect your users to AAD when hitting a protected resource (i.e when catching a 401 response), the best option is to enable the automatic
mode:
app.UseOpenIdConnectAuthentication(options => {
options.AutomaticAuthentication = true;
options.ClientId = Configuration.Get("AzureAd:ClientId");
options.Authority = String.Format(Configuration.Get("AzureAd:AadInstance"), Configuration.Get("AzureAd:Tenant"));
options.RedirectUri = "https://localhost:44300";
options.PostLogoutRedirectUri = Configuration.Get("AzureAd:PostLogoutRedirectUri");
options.Notifications = new OpenIdConnectAuthenticationNotifications {
AuthenticationFailed = OnAuthenticationFailed
};
});