3

我制作了一个网站,其中的页面包含剃须刀表单。用户可以在此表单上登录,然后重定向到不同的页面。登录(和注销)成功地与表单验证一起工作。但是,我似乎无法使用 HttpContext.Current.User.Identity.Name 来检索存储的用户名(在表单身份验证 cookie 中)。它返回一个空字符串“”。

我正在使用没有标准成员资格或角色提供者的 MVC 5 和 ASP 4.5。

登录:

 [HttpPost]
        public ActionResult Login(User user)
        {
            if (ModelState.IsValid)
            {
                bool authenticated = userscontroller.isAuthorized(user.Email, user.Password);
                if (authenticated)
                {
                    if (userscontroller.isAuthenticated())
                    {
                        userscontroller.deAuthenticateUser();
                    }
                    userscontroller.authenticateUser(user);
                    return Redirect(Url.Action("Index", "Home"));
                }
            }
        }

验证用户:

 public void authenticateUser(User user)
    {
        FormsAuthentication.SetAuthCookie(user.Username, false);
    }

然后获取用户名:

public User userFromCookie()
{
    if (isAuthenticated())
    {
        return getUserByUsername(HttpContext.Current.User.Identity.Name);
    }
    else { return null; }
}

经过身份验证()

public bool isAuthenticated()
{
    if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
    {
        return true;
    }
    else
    {
        return false;
    }
}

网络配置:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
 <authorization > <deny users="?"/> </authorization>

所以identity.name 返回“”。

帮助表示赞赏!

4

1 回答 1

8

它不起作用的可能原因。

  1. 你只是说错了。尝试this.User.Identity.Name
  2. cookie 没有保存在 Response 对象中,因此用户实际上没有在下一个请求中进行身份验证。
  3. 您没有将 web.config 配置为使用带有 cookie 的表单身份验证。

这是我为您创建的一个完整的示例。整个过程都有效,唯一的依赖是 Newtonsoft 库,但您可以删除它并将任何您想要的内容放入用户数据中。

这是用户控制器

using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace TestAuth.Controllers
{
    public class UserModel
    {
        public string UserName { get; set; }
        public string Password { get; set; }
        public bool RememberMe { get; set; }
    }

    public class UserInfo
    {
        public string UserName { get; set; }
    }

    public class UserController : Controller
    {
        [AllowAnonymous]
        public ActionResult Login()
        {
            var model = new UserModel() {Password = "password",UserName = "ItsMe", RememberMe = true};
            var serializedUser = Newtonsoft.Json.JsonConvert.SerializeObject(model);

            var ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddHours(3), model.RememberMe, serializedUser);
            var encryptedTicket = FormsAuthentication.Encrypt(ticket);
            var isSsl = Request.IsSecureConnection; // if we are running in SSL mode then make the cookie secure only

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
            {
                HttpOnly = true, // always set this to true!
                Secure = isSsl,
            };

            if (model.RememberMe) // if the user needs to persist the cookie. Otherwise it is a session cookie
                cookie.Expires = DateTime.Today.AddMonths(3); // currently hard coded to 3 months in the future

            Response.Cookies.Set(cookie);

            return View(); // return something
        }

        [Authorize]
        public ActionResult ShowUserName()
        {
            return View(new UserInfo() {UserName = this.User.Identity.Name});
        }
    }
}

以下是观点。查看Login.cshtml

Logged in
<br/>

@Html.ActionLink("Show the user their name", "ShowUserName", "User")

查看ShowUserName.cshtml

@model TestAuth.Controllers.UserInfo

<h2>title</h2>
user name = @Model.UserName

web.config 部分 请注意,密钥是从谷歌搜索中出现的某个网站生成的。您可能应该考虑自己使用正确的加密类型,因为我使用的网站有些过时了。

  <system.web>
        <authentication mode="Forms">
            <forms name="myAuthCookie" ticketCompatibilityMode="Framework40" cookieless="UseCookies" requireSSL="false" timeout="180" protection="Encryption" />
        </authentication>
        <machineKey
  validationKey="DA87693F33607268657E61BCF16D2EAFE339ECE0F6C9B94DFA0FE5BBCA0035EB320F81662A32D98F0A0D2A5DCBE3E678EDF216FBD45CB8BD6F13489D1548214C"
  decryptionKey="26F44FEF28C3466FAB261CEF4844535678578C6658F85C6ADAE17A99B0947468"
  validation="SHA1" decryption="AES"/>


        <compilation debug="true" targetFramework="4.6"/>
    <httpRuntime targetFramework="4.6"/>
  </system.web>
于 2015-09-17T10:38:12.943 回答