使用 MVC5 的 FormsAuthentication

FormsAuthentication with MVC5

在 MVC5 中 ASP.Identity 替换了旧的表单身份验证。但是根据讨论 here A type of FormsAuthentication still exists though. According to Microsoft,

但我还发现 Microsoft.Owin.Security.Forms 库也已弃用 (check this nuget link)

如果我想使用 ASP.NET MVC5 并且我想在 SQL table 中存储用户 ID 和密码(例如 aspnet_users & aspnet_membership SQL tables) (在我们迁移到新的 OpenIdConnect 之前,这应该是一个快速的临时解决方案)

ASP.NET Identity 确实支持开箱即用的基于 cookie 的身份验证,允许您将登录信息存储在数据库中并具有 "forms authentication like" 机制。默认表架构与成员资格不同,但可以自定义。

引导示例:

[assembly: OwinStartup(typeof(YourNamespace.Startup))]
namespace YourNamespace
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var options = GetCookieOptions();
            app.UseCookieAuthentication(options);
        }

        public static CookieAuthenticationOptions GetCookieOptions()
        {
            var options = new CookieAuthenticationOptions
            {
                AuthenticationType = 
                    DefaultAuthenticationTypes.ApplicationCookie,
                SlidingExpiration = true,

                // On ajax calls, better have a 401 rather than a redirect
                // to an HTML login page.
                // Taken from http://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/
                Provider = new CookieAuthenticationProvider
                {
                    OnApplyRedirect = ctx =>
                    {
                        if (!IsAjaxRequest(ctx.Request))
                        {
                            // Patching by the way the absolute uri using http
                            // instead of https, when we are behind a lb
                            // terminating the https: returning only
                            // PathAndQuery
                            ctx.Response.Redirect(new Uri(ctx.RedirectUri)
                                .PathAndQuery);
                        }
                    }
                }
            };

            if (!string.IsNullOrEmpty(Settings.Default.LoginPath))
                options.LoginPath = new PathString(Settings.Default.LoginPath);
            if (!string.IsNullOrEmpty(Settings.Default.AuthCookieName))
                options.CookieName = Settings.Default.AuthCookieName;
            if (!string.IsNullOrEmpty(Settings.Default.AuthCookieDomain))
                options.CookieDomain = Settings.Default.AuthCookieDomain;
            if (Settings.Default.ForceSecuredCookie)
                options.CookieSecure = CookieSecureOption.Always;
            return options;
        }

        // Taken from http://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/
        private static bool IsAjaxRequest(IOwinRequest request)
        {
            var query = request.Query;
            if (query != null && StringComparer.OrdinalIgnoreCase.Equals(
                query["X-Requested-With"], "XMLHttpRequest"))
                return true;
            var headers = request.Headers;
            return headers != null && StringComparer.OrdinalIgnoreCase.Equals(
                headers["X-Requested-With"], "XMLHttpRequest");
        }
    }
}

Settings.Default. 是那些示例中项目的自定义配置属性。)

签到、签出示例:

UserManager<IdentityUser> yourUserManager;

public bool SignIn(string login, string password, bool rememberMe)
{
    var user = yourUserManager.Find(userName, password);
    if (user == null)
        return false;
    var expiration = rememberMe ?
        Settings.Default.PermanentAuthCookieExpiration : 
        Settings.Default.AuthCookieExpiration;

    var authenticationManager = 
        HttpContext.Current.GetOwinContext().Authentication;

    var claimsIdentity = yourUserManager.CreateIdentity(user,
        DefaultAuthenticationTypes.ApplicationCookie);
    authenticationManager.SignIn(
        new AuthenticationProperties
        {
            AllowRefresh = true,
            IssuedUtc = DateTime.UtcNow,
            ExpiresUtc = DateTime.UtcNow.AddMinutes(expiration),
            IsPersistent = rememberMe
        }, claimsIdentity);
    return true;
}

public void IIdentityUserManager.SignOut()
{
    var authenticationManager = 
        HttpContext.Current.GetOwinContext().Authentication;
    authenticationManager.SignOut();
}

当然,对于 MVC,使用 AuthorizeAttribute 作为全局过滤器以及 [AllowAnonymous] 不需要授权的操作。