.NET 4.5.1 中的身份验证更改

Authentication changes in .NET 4.5.1

我对 .NET 4.5 有一些了解,但对 4.5.1 完全陌生。正如我所读,它们有一些变化,因此应用程序可以与 Identity 一起工作,这对于规模化的网络应用程序来说非常好。

话虽这么说,我需要开发一个带有基本 user/password 登录系统的网络应用程序,我想知道这个模板 Individual User Accounts 是否可以工作,或者我是否必须使用No Authentication?请解释你的答案。

basic user/password login system

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

但是,如果您只需要简单的 FormAuthentication,您想要 select No Authentication.

下面是简单的例子 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();
}