使用formsauthentication进行登录并使用HttpContext.Current.User.Identity

Kra*_*han 3 c# model-view-controller formsauthentication

我创建了一个网页,其中包含一个包含剃刀形式的页面.用户可以登录此表单,然后重定向到其他页面.登录(和注销)成功地与formsauthentication一起使用.但是,我似乎无法使用HttpContext.Current.User.Identity.Name来检索存储的用户名(在formsauthentication 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"));
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

验证用户:

 public void authenticateUser(User user)
    {
        FormsAuthentication.SetAuthCookie(user.Username, false);
    }
Run Code Online (Sandbox Code Playgroud)

然后获取用户的名称:

public User userFromCookie()
{
    if (isAuthenticated())
    {
        return getUserByUsername(HttpContext.Current.User.Identity.Name);
    }
    else { return null; }
}
Run Code Online (Sandbox Code Playgroud)

isauthenticated()

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

Webconfig:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
 <authorization > <deny users="?"/> </authorization>
Run Code Online (Sandbox Code Playgroud)

所以identity.name返回"".

感谢帮助!

Igo*_*gor 7

可能的原因它不起作用.

  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});
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是观点.查看Login.cshtml

Logged in
<br/>

@Html.ActionLink("Show the user their name", "ShowUserName", "User")
Run Code Online (Sandbox Code Playgroud)

查看ShowUserName.cshtml

@model TestAuth.Controllers.UserInfo

<h2>title</h2>
user name = @Model.UserName
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)