登录后,Azure AD自动注销

时间:2019-05-24 08:38:39

标签: asp.net-mvc azure azure-active-directory openid-connect

我已经尽可能多地浏览了我的帖子,而我似乎无法解决这个问题!

我的客户希望我们允许通过我构建的MVC平台登录其ADFS,因此我试图允许他们登录其Azure AD以登录该平台。

当我重定向到我的Azure AD(MS登录)登录页面时,我输入凭据,然后好像正在执行快速重定向循环,然后自动将我注销,我快疯了!!!

下面是我已设置的所有内容:

在Azure AD上:

  • 创建了App服务,并将ApplicationId和TenantId放入我的Web.config

    <add key="ida:ClientId" value="ApplicationID from AzureAD" />

    <add key="ida:Tenant" value="TenantId from AzureAD" />

    <add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" />

    <add key="ida:RedirectUri" value="https://sitename.azurewebsites.net/Home/Index" />

    <add key="ida:PostLogoutRedirectUri" value="https://sitename.azurewebsites.net" />

在Startup.Auth.cs上

public partial class Startup
    {

        // Calling the keys values from Web.config file  
        private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
        private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];

        // Concatenate aadInstance, tenant to form authority value       
        private string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

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

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            //app.UseCookieAuthentication(new CookieAuthenticationOptions());

            //Enable the application to use a cookie to store information for the signed in user

            //and to use a cookie to temporarily store information about a user logging in with a third party login provider

            //Configure the sign in cookie

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(

                            new OpenIdConnectAuthenticationOptions
                            {
                                ClientId = clientId,
                                Authority = authority,
                                PostLogoutRedirectUri = postLogoutRedirectUri,
                                Notifications = new OpenIdConnectAuthenticationNotifications
                                {
                                    AuthenticationFailed = (context) =>
                                    {
                                        context.HandleResponse();
                                        context.OwinContext.Response.Redirect("/Home/Index");
                                        return Task.FromResult(0);
                                    }
                                }
                            });


        } // end - ConfigureAuth method  

在我的routeConfig上:这样做是为了可以首先加载我的自定义登录页面,此页面上是一个显示“输入平台”的按钮,客户端将单击该按钮并转到Azure AD登录(“ MS登录”页面)

public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.LowercaseUrls = true;
            routes.MapRoute("Default", "{controller}/{action}/{id}", new
            {
                controller = "Account",
                action = "Login",
                id = UrlParameter.Optional
            }).RouteHandler = new DashRouteHandler();
        }
    }

帐户控制器

[Authorize]
        public void SignIn()
        {
            clsHomeScreen clsHomeScreen = new clsHomeScreen();
            if (!Request.IsAuthenticated)
            {
                HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }

            Response.Redirect("/");
        }

[AllowAnonymous]
        [OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
        public ActionResult Login(string returnUrl)
        {
            // We do not want to use any existing identity information
            EnsureLoggedOut();

            // Store the originating URL so we can attach it to a form field
            var viewModel = new AccountLoginModel { ReturnUrl = returnUrl };

            return View(viewModel);
        }

HomeController-登录后应将其重定向到该位置,但不能:

[Authorize]
        public async Task<ActionResult> Index()
        {
            HomeScreenLists HS = new HomeScreenLists();
            IEnumerable<Challenges> ActiveChallenges;
            IEnumerable<Challenges> PrivateChallenges;
            string loggedInUserId = "";
            string loggedInEmail = "";
            var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;

            string email = userClaims?.FindFirst(System.IdentityModel.Claims.ClaimTypes.Name)?.Value;
            string firstname = userClaims?.FindFirst(System.IdentityModel.Claims.ClaimTypes.GivenName)?.Value;
            string lastname = userClaims?.FindFirst(System.IdentityModel.Claims.ClaimTypes.Surname)?.Value;
            string userId = "";

            //The Email will not contain an @(i.e. an email address) if not using Azure AD to sign in.
            if (!email.Contains("@"))
            {
                loggedInUserId = User.Identity.GetUserId();
                goto LoggedInUser_Found;
            }

            if (TempData["LoggedInEmail"] != null)
            {
                if (email != TempData["LoggedInEmail"].ToString())
                {
                    userId = clsHomeScreen.GetUserId(TempData["LoggedInEmail"].ToString());
                }
                else
                {
                    userId = clsHomeScreen.GetUserId(email);
                }
            }

            if (email != null)
            {
                userId = clsHomeScreen.GetUserId(email);
            }

            if (userId == null || userId == "")
            {
                clsUsers clsUsers = new clsUsers();

                if (TempData["LoggedInEmail"] != null)
                {
                    loggedInEmail = TempData["LoggedInEmail"].ToString();

                    var userDetails = clsUsers.GetUsers().Where(x => x.Email == loggedInEmail).FirstOrDefault();
                    loggedInUserId = userDetails.Id;
                }
                else
                {
                    if(userId == null)
                    {
                        await RegisterAAD();
                        userId = clsHomeScreen.GetUserId(email);
                        loggedInUserId = userId;
                    }
                    else
                    {
                        loggedInUserId = User.Identity.GetUserId();
                    }

                }
            }
            else
            {
                loggedInUserId = userId;
            }

            LoggedInUser_Found:

            int iBU = (int)db.Users.FirstOrDefault(x => x.Id == loggedInUserId).fkiBusinessUnitId;

            if (iBU == 0)
            {
                HS.HasBU = false;
                TempData["HasBU"] = "No";
                TempData["UserId"] = loggedInUserId;
            }
            else
            {
                HS.HasBU = true;
                TempData["HasBU"] = "Yes";
                TempData["UserId"] = loggedInUserId;
            }

            bool isAdmin = false;

            if (User.IsInRole("Administrator"))
            {
                isAdmin = true;
            }

            ActiveChallenges = clsChallenges.GetActiveChallenges();
            PrivateChallenges = clsChallenges.GetPrivateChallenges(loggedInUserId, isAdmin);

            HS.HomeScreenList = clsHomeScreen.GetHomeScreenAdverts();

            HS.ActiveChallengesList = ActiveChallenges;
            HS.PrivateChallengesList = PrivateChallenges;

            HS.UserId = loggedInUserId;

            return View(HS);
        }

因此,如果我删除索引ActionResult上的[Authorize]属性,则它将进行连续重定向循环。

我试过的是什么

  • 我尝试使用KentorCookiSaver,但没有用。
  • 重新创建应用程序服务
  • 更改了Azure AD应用程序注册中的redirectUrl
  • 甚至有人谈论过重写cookie的尝试,但是我不知道我是否正确地遵循了步骤,链接是Here

我尝试了很多事情,以至于我什至不记得我所尝试过的。请问有人可以帮我解决我做错的事情。

感谢一百万!

1 个答案:

答案 0 :(得分:0)

因此,在了解这些事情的人的帮助下,我的问题得以解决。

最终归结为:

  • 我需要将RedirectUri添加到Web.config和Startup.Auth

Web.Config

<add key="ida:RedirectUri" value="https://sitename.azurewebsites.net/Home/Index"/>

Startup.Auth

 app.UseOpenIdConnectAuthentication(

                            new OpenIdConnectAuthenticationOptions
                            {
                                ClientId = clientId,
                                Authority = authority,
                                RedirectUri = redirectUri,
                                PostLogoutRedirectUri = postLogoutRedirectUri,
                                Notifications = new OpenIdConnectAuthenticationNotifications
                                {
                                    AuthenticationFailed = (context) =>
                                    {
                                        context.HandleResponse();
                                        context.OwinContext.Response.Redirect("/Home/Index");
                                        return Task.FromResult(0);
                                    }
                                }
                            });
  • 我的登录过程在失败时应该路由回到我的“帐户/登录”页面,当它应该路由到我的“首页/索引”时,因为我使用“帐户/登录”作为我的登录页面,并且身份验证仅在此之后发生,之所以发生这种情况,是因为我在“帐户/登录”上做了一个“ EnsureLogOut”,因此为什么它在希望进行身份验证之前一直先注销我。因此,我更改为Redirect =“ /”,如下所示:

public void SignIn()

    `{`

        `clsHomeScreen clsHomeScreen = new clsHomeScreen();`

        `if (!Request.IsAuthenticated)`

        `{`

            `HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/Home/Index" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);`

        `}`


        `Response.Redirect("/Home/Index");`

    `}`

也许这可能对别人没有帮助,但也许可以在正确的方向帮助他们。