表单身份验证中的声明

时间:2017-06-16 15:18:53

标签: c# asp.net asp.net-mvc asp.net-mvc-4 authentication

我正在使用Forms身份验证的asp.net MVC网站工作。

该网站有一个登录页面,成功登录后会显示某些用户数据。

问题是userName或userId在发布后总是返回null。

好像声明在帖子之后丢失了

问候,豪尔赫

这是web.config

<system.web> <authentication mode="Forms"> <forms name="SingleSignOn" loginUrl="~/User/Login" timeout="480" slidingExpiration="true"/> </authentication> <machineKey validationKey="E4451576F51E0562D91A1748DF7AB3027FEF3C2CCAC46D756C833E1AF20C7BAEFFACF97C7081ADA4648918E0B56BF27D1699A6EB2D9B6967A562CAD14767F163" decryptionKey="6159C46C9E288028ED26F5A65CED7317A83CB3485DE8C592" validation="HMACSHA256" decryption="AES" /> <compilation targetFramework="4.5.1" debug="true"/> <httpRuntime targetFramework="4.5.1"/> </system.web>

此代码显示了身份验证私有方法:

 private void AuthenticateUser(string username, bool createPersistenceCookie)
{
  FormsAuthentication.SignOut();
  FormsAuthenticationTicket newAuthTicket = new FormsAuthenticationTicket(username, true, 1);

  FormsIdentity formsIdentity = new FormsIdentity(newAuthTicket);

  var user = (from c in db.Clients
              where c.UserName == username
              select c).SingleOrDefault();

  var claims = new List<Claim>();
  claims.Add(new Claim("UserName", username));
  claims.Add(new Claim("Id", user.ID.ToString()));
  claims.Add(new Claim(ClaimTypes.Name, user.Name));
  claims.Add(new Claim(ClaimTypes.Email, user.Email ?? ""));
  // Required for AntiForgeryToken
  claims.Add(new Claim(ClaimTypes.NameIdentifier, user.ID.ToString()));
  claims.Add(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", user.ID.ToString()));
  claims.Add(new Claim("IsAdUser", user.IsAdUser.ToString()));

  var extendedRoles = CalculateEmployeeExtendedRoles(user);
  foreach (var role in extendedRoles)
    claims.Add(new Claim(ClaimTypes.Role, role));

  //Add a claim for the User Name
  formsIdentity.AddClaims(claims);

  //Attach the new principal object to the current HttpContext object
  HttpContext.User = new System.Security.Principal.GenericPrincipal(formsIdentity, new string[] { });

  //Make sure the Principal's are in sync
  System.Threading.Thread.CurrentPrincipal = HttpContext.User;

  //Set the Forms Authentication Cookie
  FormsAuthentication.SetAuthCookie(username, createPersistenceCookie);
}

这是显示用户信息的剃刀视图

@using Microsoft.AspNet.Identity

@if (Request.IsAuthenticated)
{
  using (Html.BeginForm("LogOut", "User", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
  {
    @Html.AntiForgeryToken()

    <ul class="nav navbar-nav navbar-right">
      <li>
        @Html.ActionLink("Hola " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
      </li>
      
      <li><a href="javascript:document.getElementById('logoutForm').submit()">Cerrar sesión</a></li>
    </ul>
  }
}

0 个答案:

没有答案