使用表单身份验证进行登录并使用HttpContext.Current.User.Identity [英] Using formsauthentication for login and use HttpContext.Current.User.Identity

查看:348
本文介绍了使用表单身份验证进行登录并使用HttpContext.Current.User.Identity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个网站,其页面包含剃须刀形式.用户可以登录此表单,然后重定向到其他页面. 登录(和注销)可以成功进行表单身份验证.但是,我似乎无法使用HttpContext.Current.User.Identity.Name来检索存储的用户名(在表单身份验证cookie中).它返回一个空字符串".

I have made a website with a page that includes a razor form. The user can login on this form and then redirects to a different page. The logging in (and logging out) works with formsauthentication succesfully. However, I can't seem to use HttpContext.Current.User.Identity.Name to retrieve the stored username (in the formsauthentication cookie). It returns an empty string "".

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

I am using MVC 5 and ASP 4.5 with no standard membership or role providers.

登录:

 [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; }
}

isauthenticated()

isauthenticated()

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

Webconfig:

Webconfig:

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

因此,identity.name返回".

So the identity.name returns "".

感谢您的帮助!

推荐答案

可能不起作用.

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

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

Here is a fully working example I created for you. This whole thing works, the only dependency is on a Newtonsoft library but you could remove that and put anything you want in the user data.

这是用户控制器

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部分 请注意,密钥是从google搜索中出现的某个网站生成的.由于我使用的网站有些过时,您可能应该考虑自己拥有并使用正确的加密类型.

  <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>

这篇关于使用表单身份验证进行登录并使用HttpContext.Current.User.Identity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆