Search code examples
asp.net-mvcoauth-2.0owinopenid-connectadal

MVC OpenId Microsoft Idenity GetExternalLoginInfoAsync null


I am trying to implement Microsoft Identity in my existing Azure Cloud service. The Cloud Service consists of a ASP.NET MVC 5 web role. I am using the UseOpenIdConnectAuthentication middleware.

The application succesfully redirects the user to the Microsoft signin page. After that the application just prompts back to the application's login page, and the user is not logged in. When I check the ExternalLoginCallback function in the AccountController, the value of AuthenticationManager.GetExternalLoginInfoAsync() returns null. The code in Startup.Auth.cs is:

public void ConfigureAuth(IAppBuilder app)
{
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
        {
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
        }
    });
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
    {
        Authority = "https://login.microsoft.com/common/v2.0",
        ClientId = "-----client id is here------",
        Scope = "openid email",
        RedirectUri = "https://localhost",
        TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false
        }
    }
    );
}

I checked if the token was available in the OnAuthorizationCodeReceived event, and it was. notification.JwtSecurityToken contained the requested information.

Does somebody have any clue why the GetExternalLoginInfoAsync() is returning a null value, while the token is actually received by the application?


Solution

  • I finally found a solution for the problem. There is some kind of bug in Katana where cookies are mysteriously overwritten.

    I have used the Kentor OwinCookieSaver nuget package to resolve this issue.

    I have placed it above all cookie auth properties such as app.UseCookieAuthentication. The order in which you place the Owin middleware makes sense. I don't know if this is the best order, but this works for me!