使用MVC5进行FormsAuthentication

时间:2016-05-04 22:08:12

标签: asp.net-mvc asp.net-identity forms-authentication

在MVC5中,ASP.Identity取代了旧的表单身份验证。但是根据讨论here但仍然存在一种FormsAuthentication。 According to Microsoft,

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

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

1 个答案:

答案 0 :(得分:1)

ASP.NET Identity支持开箱即用的基于cookie的身份验证,允许您在数据库中存储登录并具有"表单身份验证,如"机制。默认表模式与成员资格不同,但可以自定义。

引导样本

[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]一起用作不需要授权的操作的全局过滤器。