.NET 4.5.1中的身份验证更改

时间:2015-02-04 23:25:22

标签: asp.net .net asp.net-mvc

我对。NET 4.5 有一些了解,但对 4.5.1 完全陌生。在我阅读时,他们进行了一些更改,以便应用程序与Identity一起使用,这对于扩展网络应用程序非常有用。

话虽这么说,我需要使用基本的用户/密码登录系统开发一个Web应用程序,我想知道这个模板Individual User Accounts是否可行,或者我是否必须使用{{ 1}?请解释一下你的答案。

1 个答案:

答案 0 :(得分:2)

  

基本用户/密码登录系统

个人用户帐户将为您配置 ASP.Net Identity 。此外,它还将创建基本登录,注销和其他额外模板。点击Learn more了解更多信息。

enter image description here

但是,如果您只需要简单的 FormAuthentication ,则需要选择无身份验证

以下是简单 FormAuthentication 的示例。

登录方法

public void SignIn(string username, bool createPersistentCookie)
{
    var now = DateTime.UtcNow.ToLocalTime();
    TimeSpan expirationTimeSpan = FormsAuthentication.Timeout;

    var ticket = new FormsAuthenticationTicket(
        1 /*version*/,
        username,
        now,
        now.Add(expirationTimeSpan),
        createPersistentCookie,
        "" /*userData*/,
        FormsAuthentication.FormsCookiePath);

    var encryptedTicket = FormsAuthentication.Encrypt(ticket);

    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, 
        encryptedTicket)
    {
        HttpOnly = true,
        Secure = FormsAuthentication.RequireSSL,
        Path = FormsAuthentication.FormsCookiePath
    };

    if (ticket.IsPersistent)
    {
        cookie.Expires = ticket.Expiration;
    }
    if (FormsAuthentication.CookieDomain != null)
    {
        cookie.Domain = FormsAuthentication.CookieDomain;
    }

    Response.Cookies.Add(cookie);
}

的Global.asax.cs

您需要这样才能从cookie中检索用户名,并将其保存在IPrincipal对象中。

public class Global : HttpApplication
{
    private void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie decryptedCookie =
            Context.Request.Cookies[FormsAuthentication.FormsCookieName];

        FormsAuthenticationTicket ticket =
            FormsAuthentication.Decrypt(decryptedCookie.Value);

        var identity = new GenericIdentity(ticket.Name);
        var principal = new GenericPrincipal(identity, null);

        HttpContext.Current.User = principal;
        Thread.CurrentPrincipal = HttpContext.Current.User;
    }
}

的web.config

确保您在web.config中有身份验证标记。

例如,

<authentication mode="Forms">
   <forms loginUrl="~/Account/Login" />
</authentication>

用法

public ActionResult Index()
{
    var username = User.Identity.Name;

    return View();
}
相关问题