SSO:2个项目:自动登录第二个项目

时间:2014-10-20 16:05:18

标签: c# authentication model-view-controller single-sign-on cross-site

我必须投射项目:我自己,我们称之为Intranet,第二个:MVCForum(http://mvcforum.com)。 目标:当用户登录我的Intranet并单击论坛链接时 - 他会自动重定向并登录。

到目前为止,我可以将数据(用户登录名+密码)发送到MVCForum MembersController中的LogOn方法。它非常好,一切似乎与我通常登录论坛时完全一样。但是一些如何被重定向后(从论坛的登录页面到论坛的主站点)我没有登录:(

我花了最近3天才得到这个,什么都没有。 内联网:localhost:55123 论坛:localhost:9666 论坛有一个数据库,内联网有一个数据库:没有相互连接 - 现在我将离开这个。

两个项目都在一个解决方案中。  这是我的代码: 1.我的重定向到论坛(在其中一个内部网控制器中):

public async Task<ActionResult> Forum()
    {

        string url = "http://localhost:9666/Members/Logon";
        Uri address = new Uri(url);
        var postData = new List<KeyValuePair<string, string>>
                           {
                               new KeyValuePair<string, string>("UserName", "admin"),
                               new KeyValuePair<string, string>("Password", "password"),
                                new KeyValuePair<string, string>("RememberMe", "False")
                           };

        HttpContent content = new FormUrlEncodedContent(postData);
        var cookieJar = new CookieContainer();
        var handler = new HttpClientHandler
        {
            CookieContainer = cookieJar,
            UseCookies = true,
            UseDefaultCredentials = false
        };

        var client = new HttpClient(handler)
        {
            BaseAddress = address
        };


        HttpResponseMessage response = await client.PostAsync(url, content);
        response.EnsureSuccessStatusCode();
        string body = await response.Content.ReadAsStringAsync();

        Uri uri = new Uri(url);
        var responseCookies = cookieJar.GetCookies(uri);
        foreach (Cookie cookie in responseCookies)
        {
            cookieJar.Add(cookie);
            string cookieName = cookie.Name;
            string cookieValue = cookie.Value;
            this.Response.Cookies.Add(new HttpCookie(cookie.Name, cookie.Value){Domain = cookie.Domain, Expires = cookie.Expires});
        }

        var person = new Person { Name = "name1" };

        var mod = new LogOnViewModel
                      {
                          Password = "password",
                          RememberMe = false,
                          ReturnUrl = null,
                          UserName = "admin"
                      };


        return this.Redirect("http://localhost:9666/"); 
    }
  1. 内联网的web.config:
  2.  <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" name=".ASPXFORMSAUTH"
             protection="Validation"
             path="/"
             domain="localhost"/>
    </authentication>
    <machineKey validationKey="D4499A4E3540646431DAFBA7462C3A8220447D7C49DEA6F6A2DD94D9A400DBBEBDC8020856FD91B353087716C3E320902508249FEDA4F10E517F799669ADA762"
             decryptionKey="897B17754EB63518A45E9C209B7ADD542B5D09B4D2ED03C024EF07E4BF169387"
             validation="SHA1" decryption="Auto" compatibilityMode="Framework20SP1"/>
    
    1. MVCForum中的登录方法:

      public ActionResult LogOn(LogOnViewModel model)     {         使用(var unitOfWork = UnitOfWorkManager.NewUnitOfWork())         {             var username = model.UserName;             var password = model.Password;

              try
              {
                  if (ModelState.IsValid)
                  {
                      var message = new GenericMessageViewModel();
                      var user = new MembershipUser();
                      if (MembershipService.ValidateUser(username, password, System.Web.Security.Membership.MaxInvalidPasswordAttempts))
                      {
                          // Set last login date
                          user = MembershipService.GetUser(username);
                          if (user.IsApproved && !user.IsLockedOut)
                          {
                              FormsAuthentication.SetAuthCookie(username, model.RememberMe);
                              HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(15),false,user.Id.ToString() )));
      
                              Response.Cookies.Add(cookie);
                              user.LastLoginDate = DateTime.UtcNow;
      
                              if (Url.IsLocalUrl(model.ReturnUrl) && model.ReturnUrl.Length > 1 && model.ReturnUrl.StartsWith("/")
                                  && !model.ReturnUrl.StartsWith("//") && !model.ReturnUrl.StartsWith("/\\"))
                              {
                                  return Redirect(model.ReturnUrl);
                              }
      
                              message.Message = LocalizationService.GetResourceString("Members.NowLoggedIn");
                              message.MessageType = GenericMessages.success;
      
                              return RedirectToAction("Index", "Home", new { area = string.Empty });
                          }
      
                      }
      
                      // Only show if we have something to actually show to the user
                      if (!string.IsNullOrEmpty(message.Message))
                      {
                          TempData[AppConstants.MessageViewBagName] = message;
                      }
                      else
                      {
                        (...)
                          }
                      }
                  }
              }
      
              finally
              {
                  try
                  {
                      unitOfWork.Commit();
                  }
                  catch (Exception ex)
                  {
                      unitOfWork.Rollback();
                      LoggingService.Error(ex);
                  }
      
              }
      
              return View(model);
          }
      }
      
    2. MVCForum项目的web.config:

    3. <authentication mode="Forms">
        <forms loginUrl="~/members/logon" timeout="2880"  name=".ASPXFORMSAUTH"
               protection="Validation"
               path="/"
               domain="localhost"/>
      </authentication>
      <machineKey validationKey="D4499A4E3540646431DAFBA7462C3A8220447D7C49DEA6F6A2DD94D9A400DBBEBDC8020856FD91B353087716C3E320902508249FEDA4F10E517F799669ADA762"
                decryptionKey="897B17754EB63518A45E9C209B7ADD542B5D09B4D2ED03C024EF07E4BF169387"
                validation="SHA1" decryption="Auto" compatibilityMode="Framework20SP1"/>
      

      我真的不明白为什么它不起作用。不知道其他代码可能会有什么帮助。 machineKey和cookie名称是相同的,因为我读到它必须是相同的,所以我可以实现我想要的。 请帮帮我。

0 个答案:

没有答案