1

After Logging in from Azure AD I am getting Claims Based Identity e.g. UserName, Logi-Email null and Authentication is also False in Browser Chrome, Firefox but not in Microsoft Edge. This usually happens randomly and also when I log-out and re-login in Chrome browser the user authentication shows false in debug mode and claims are null. Let me know whats the problem area, I have researched with no avail.

Note- AddAuthentication().AddOpenIdConnect are for asp.netcore where as I am using asp.net mvc 5

   app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                // AuthenticationMode = AuthenticationMode.Passive,
                ClientId = ClientId,
                Authority = AuthenticationConfig.Authority,
                RedirectUri = AuthenticationConfig.RedirectUri,
                PostLogoutRedirectUri = AuthenticationConfig.PostLogoutRedirectUri,
                Scope = AuthenticationConfig.BasicSignInScopes,
                ResponseType = OpenIdConnectResponseType.IdToken,
                TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = false, NameClaimType = "name" },   //this.BuildTokenValidationParameters(),
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = (context) =>
                    {
                        // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                        // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
                        // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                        string appRedirectUri = string.Format("{0}://{1}{2}", context.Request.Scheme, (context.Request.Host.ToString() + context.Request.PathBase), AuthenticationConfig.RedirectUriAbsolutePath);
                        string postLogOutRedirectUri = string.Format("{0}://{1}{2}", context.Request.Scheme, (context.Request.Host.ToString() + context.Request.PathBase), "/Dashboard/Index");
                        context.ProtocolMessage.RedirectUri = appRedirectUri;
                        context.ProtocolMessage.PostLogoutRedirectUri = postLogOutRedirectUri;
                        return Task.FromResult(0);
                    },
                    SecurityTokenValidated = (context) =>
                    {
                        // retrieve caller data from the incoming principal
                        //string issuer = context.AuthenticationTicket.Identity.FindFirst("iss").Value;
                        //string Upn = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;
                        //string tenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

                        //if (
                        //     //the caller comes from an admin-consented, recorded issuer
                        //    (this.db.Tenants.FirstOrDefault(a => ((a.IssValue == issuer) && (a.AdminConsented))) == null)
                        //            // the caller is recorded in the db of users who went through the individual on-boarding
                        //            && (this.db.Users.FirstOrDefault(b => ((b.UPN == Upn) && (b.TenantID == tenantId))) == null)
                        //            )
                        //           // the caller was neither from a trusted issuer or a registered user -throw to block the authentication flow
                        //            throw new UnauthorizedAccessException("Please use the Sign-up link to sign -up for the ToDo list application.");

                        return Task.FromResult(0);
                    },
                    AuthorizationCodeReceived = (context) =>
                    {
                        //var code = context.Code;
                        //ClientCredential credential = new ClientCredential(ClientId, AppKey);
                        //string tenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        //string signedInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                        //AuthenticationContext authContext = new AuthenticationContext(AadInstance + tenantId, new ADALTokenCache(signedInUserId));

                        //// The following operation fetches a token for Microsoft graph and caches it in the token cache
                        //AuthenticationResult result = authContext.AcquireTokenByAuthorizationCodeAsync(
                        //    code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, GraphResourceId).Result;

                        return Task.FromResult(0);
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.Response.Redirect("/Error/ShowError?signIn=true&errorMessage=" + context.Exception.Message);
                        context.HandleResponse(); // Suppress the exception
                        return Task.FromResult(0);
                    }
                },
                SignInAsAuthenticationType = "Cookies"
            });
    }
Rinkesh
  • 21
  • 8

1 Answers1

1

So after 1 week of Research. Below code in Startup.Auth.cs solved my problem. Reference: ASP.NET_SessionId + OWIN Cookies do not send to browser

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            CookieManager = new SystemWebCookieManager()
        });
Rinkesh
  • 21
  • 8