Using [Authorize] with OpenIdConnect in MVC 6 results in immediate empty 401 responses

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 the action method:

Context.Response.Challenge(
    new AuthenticationProperties { RedirectUri = "/" },
    OpenIdConnectAuthenticationDefaults.AuthenticationType);

      

However, if I try to use the attribute [Authorize]

instead, I get an immediate empty 401 response.

How can I [Authorize]

redirect properly to Azure AD?

My configuration looks like this:

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
        };
    });
    ...
}

      

+3


source to share


1 answer


To automatically redirect users to AAD when they hit a protected resource (i.e. when a 401 response is found), the best option is to enable the mode automatic

:



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
    };
});

      

+6


source







All Articles