Search code examples
asp.net-coreopenidazure-active-directory

AutomaticChallenge not working for CookieAuthentication in ASP.NET MVC Core with Azure AD sample


I am slightly altering the code from the Integrating Azure AD into an ASP.NET Core web app sample. I can run the application successfully, and if I click the "Log in" link then I correctly get redirected to the Azure AD sign-in page.

However, I also would like for the application to automatically redirect me to the login page if I try to access a route that is protected with the Authorize attribute. I have added the [Authorize] attribute to the HomeController's Contact action, but if I try to access this without being logged in, I do not get redirected to the login page. If I access the contact page while logged in then it displays correctly.

I have updated the Startup.cs file as follows:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    LoginPath = "/Account/Login"
});

But even with these changes, I don't get redirected to the login page. Is there something else I'm missing?


Solution

  • I discovered the problem. The sample references version 1.0.0 of the Microsoft.AspNetCore.Authentication.Cookies. I had upgraded the package to version 1.1.0, and hit the issue described here. Specifically, in version 1.1.0 of this package the AutomaticChallenge behaviour changed when using multiple authentication providers (which is what the sample does).

    I was able to work around the change by updating the sample's Startup.cs file's Configure method as follows:

    Change the line that calls app.UseCookieAuthentication to

    app.UseCookieAuthentication(new CookieAuthenticationOptions()
    {
        AutomaticChallenge = true
    });
    

    And in the call to app.UseOpenIdConnectAuthentication, add this line:

    AutomaticChallenge = false