加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用formsauthentication进行登录并使用HttpContext.Curre

发布时间:2020-12-15 23:27:20 所属栏目:百科 来源:网络整理
导读:我创建了一个网页,其中包含一个包含剃刀形式的页面.用户可以登录此表单,然后重定向到其他页面. 登录(和注销)成功地与formsauthentication一起使用.但是,我似乎无法使用HttpContext.Current.User.Identity.Name来检索存储的用户名(在formsauthentication cook
我创建了一个网页,其中包含一个包含剃刀形式的页面.用户可以登录此表单,然后重定向到其他页面.
登录(和注销)成功地与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"));
                }
            }
        }

验证用户:

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

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

Webconfig:

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

所以identity.name返回“”.

感谢帮助!

解决方法

可能的原因它不起作用.

>你只是说错了.试试这个.User.Identity.Name
> Cookie不会保留在Response对象中,因此用户实际上未在下一个请求中进行身份验证.
>您没有将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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读