AuthenticationManager.GetExternalLoginInfoAsync() returns null for Kentico 12 MVC

Rahul Raghuvanshi asked on March 27, 2023 13:06

I have created a Kentico application on Kentico12 MVC version v12.0.81 and .net 4.6.1 and I have setup Azure ADB2C for external authentication.

The application is running fine on dev and test environment and able to get the users data in my code returned from Azure ADB2C.

But when I deployed the application on production environment (the app is deployed on IIS server), one of the method that returns the external user info "ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();" starts returning null randomly or frequently.

When the application is deployed on production intially it runs well for some time say 5-10 mins and then the application starts showing inappropriate behaviour where the method "ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();" starts returning null and when i restart the app pool then the application again starts working for some time and then external user info starts returning as null.

FYI, Following are some of the owin packages I am using in my project:

Microsoft.AspNet.Identity.Owin - 2.2.1

Microsoft.Owin.Host.SystemWeb - 4.1.0

Microsoft.Owin.Security.Cookies - 3.1.0

Microsoft.Owin.Security.OpenIdConnect - 4.1.0

Microsoft.Owin.Security.OAuth - 3.1.0 , Microsoft.Owin.Security.WsFederation - 4.1.0

Can you please suggest for the above issue?

Thanks, Rahul

Recent Answers


Dmitry Bastron answered on March 30, 2023 17:47

Hi Rahul,

What instructions did you follow to implement this integration? Can you share some code how you are registering this authentication method?

This might be related to cookies, or session duration I think. Also, have you tried updating authentication packages to the latest versions? The ones you mentioned are not the latest versions.

0 votesVote for this answer Mark as a Correct answer

Rahul Raghuvanshi answered on April 3, 2023 16:03 (last edited on April 3, 2023 16:05)

Hi Dmitry,

I have tried updating "Microsoft.Owin" packages to latest version i.e. 4.2.2 but still facing the same issue.

Below is the piece of code for authentication I have setup:

public void Configuration(IAppBuilder app)
    {
                // Registers the Kentico.Membership identity implementation
                app.CreatePerOwinContext(() => UserManager.Initialize(app, new UserManager(new UserStore(SiteContext.CurrentSiteName))));
                app.CreatePerOwinContext<SignInManager>(SignInManager.Create);
                app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

                // Configures the authentication cookie
                UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    CookieManager = new SystemWebChunkingCookieManager(),
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    LoginPath = new PathString("/"),
                    Provider = new CookieAuthenticationProvider
                    {
                        // Sets the return URL for the sign-in page redirect (fill in the name of your sign-in action and controller)
                        OnApplyRedirect = context => context.Response.Redirect(urlHelper.Action("Index", "Logon")
                                                     + new Uri(context.RedirectUri).Query)
                    }
                });

                // Registers the authentication cookie with the 'Essential' cookie level
                // Ensures that the cookie is preserved when changing a visitor's allowed cookie level below 'Visitor'
                CookieHelper.RegisterCookie(OWIN_COOKIE_PREFIX + DefaultAuthenticationTypes.ApplicationCookie, CookieLevel.Essential);

                // Uses a cookie to temporarily store information about users signing in via external authentication services
                app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

                app.UseOpenIdConnectAuthentication(
                   new OpenIdConnectAuthenticationOptions
                   {
                       // Generate the metadata address using the tenant and policy information
                       MetadataAddress = String.Format(Globals.WellKnownMetadata, Globals.Tenant, Globals.DefaultPolicy),

                       // These are standard OpenID Connect parameters, with values pulled from web.config
                       ClientId = Globals.ClientId,
                       RedirectUri = Globals.RedirectUri,
                       PostLogoutRedirectUri = Globals.PostLogoutRedirectUri,

                       // Specify the callbacks for each type of notifications
                       Notifications = new OpenIdConnectAuthenticationNotifications
                       {
                           RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                           AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                           AuthenticationFailed = OnAuthenticationFailed,
                       },


                       // Specify the claim type that specifies the Name property.
                       TokenValidationParameters = new TokenValidationParameters
                       {
                           NameClaimType = "name",
                           ValidateIssuer = false
                       },

                       // Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
                       Scope = $"openid profile offline_access {Globals.ReadTasksScope} {Globals.WriteTasksScope}",
                   }
               );
            }

Also my logout code is as follows:

public ActionResult Logout(string returnUrl)
        {
            try
            {
                EventLogProvider.LogInformation("Logout", "AccountController", "Called Logout with return url : " + returnUrl);
                // To sign out the user, you should issue an OpenIDConnect sign out request.
                if (Request.Cookies["CurrentContact"] != null)
                {
                    Response.Cookies["CurrentContact"].Expires = DateTime.Now.AddMinutes(-1);
                }

                if (Request.Cookies["CMSViewMode"] != null)
                {
                    Response.Cookies["CMSViewMode"].Expires = DateTime.Now.AddMinutes(-1);
                }
                Task task = MsalAppBuilder.ClearUserTokenCache();
                IEnumerable<AuthenticationDescription> authTypes = HttpContext.GetOwinContext().Authentication.GetAuthenticationTypes();
                HttpContext.GetOwinContext().Authentication.SignOut(authTypes.Select(t => t.AuthenticationType).ToArray());
                Request.GetOwinContext().Authentication.GetAuthenticationTypes();
            }

            catch (Exception ex)
            {
                EventLogProvider.LogException("Logout", "Account", ex);
            }

            return RedirectToAction("Index", "Home");
        }

Please review and suggest

0 votesVote for this answer Mark as a Correct answer

Dmitry Bastron answered on April 4, 2023 09:13

Try adding this line into your new CookieAuthenticationOptions{..} block:

CookieName = OWIN_COOKIE_PREFIX + DefaultAuthenticationTypes.ApplicationCookie

I suspect the default cookie name might differ from the one you registered in CookieHelper.RegisterCookie, hence are your problems. And I think it might be related to the fact some users are not accepting cookies on your site and those users have problems with the login, rather than the application starting to behave strangely after some time.

0 votesVote for this answer Mark as a Correct answer

Rahul Raghuvanshi answered on April 4, 2023 10:37 (last edited on April 4, 2023 11:07)

I have checked but the cookie is getting added successfully with the correct name in browser as shown in the below image:

https://prnt.sc/dEluhW-FPNSV

Browser Cookie

But will try adding the line you suggested within the "new CookieAuthenticationOptions{..}" block.

Also, within the logout functionality logic as I am seeing three cookies "OpenIdConnect", "ApplicationCookie" and "ExternalCookie" is getting removed as shown in the below screenshot:

https://prnt.sc/i6f_zXoos0yp

Cookies

But at the time of logging in i am able to see"ApplicationCookie" added in the browser, but the "ExternalCookie" and "OpenIdConnect" cookie is now showing in the browser. Can you please suggest where can i see these cookies?

Please suggest.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.