Azure AD после проблем со входом в систему, утверждения недействительны в веб-браузере (Chrome, Firefox)

После входа в Azure AD я получаю удостоверение на основе утверждений, например. UserName, Logi-Email null и Authentication также имеют значение False в браузере Chrome, Firefox, но не в Microsoft Edge. Обычно это происходит случайным образом, а также, когда я выхожу из системы и снова вхожу в нее в браузере Chrome, аутентификация пользователя показывает false в режиме отладки, а утверждения являются нулевыми. Дайте мне знать, в чем проблема, я исследовал безрезультатно.

Примечание. AddAuthentication(). AddOpenIdConnect предназначены для asp.netcore, где я использую 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"
            });
    }

person Rinkesh    schedule 06.09.2020    source источник


Ответы (1)


Итак, после 1 недели исследований. Код ниже в Startup.Auth.cs решил мою проблему. Ссылка: ASP.NET_SessionId + OWIN Cookies не отправляются браузер

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            CookieManager = new SystemWebCookieManager()
        });
person Rinkesh    schedule 08.09.2020