代码改变世界

【MVC5】使用域用户登录+记住我

2015-10-27 09:46 by JiaJia.Oct, ... 阅读, ... 评论, 收藏, 编辑

1.配置Web.config文件

  • 添加域链接字符串

<connectionStrings>
    <add name="ADConnectionString" connectionString="LDAP://DC1.xxx.com.cn:389/DC=xxx,DC=com,DC=cn" />
  </connectionStrings>
  • 添加membership

<system.web>
    <membership defaultProvider="ADMembershipProvider">
      <providers>
        <clear />
        <add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" />
      </providers>
    </membership>
  </system.web>

2.代码中使用配置好的Membership来验证用户登录信息

public ActionResult Login(LoginModel model, string returnUrl)
{
    if (!this.ModelState.IsValid)
    {
        return this.View(model);
    }

    if (Membership.ValidateUser(model.UserId, model.Password))
    {
        MembershipUser user = Membership.GetUser(model.UserId);
        // 用户角色
        List<string> roles = new List<string>();
        
        ... 
        
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
            1, 
            model.UserId, 
            DateTime.Now, 
            DateTime.Now.AddDays(30),    // 设置记住登录的时间(这里是30天)
            true,
            String.Join(",", roles));
        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
        // 设置cookie的过期时间(这里是50年)
        cookie.Expires = DateTime.Now.AddYears(50);
        Response.Cookies.Add(cookie);

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

    this.ModelState.AddModelError(string.Empty, "用户名或密码错误。");

    return this.View(model);
}

已添加到【MVC5】ASP.NET MVC 项目笔记汇总