使用MVC5进行表单身份验证



在MVC5中,ASP.Identity取代了旧的表单身份验证。然而,根据这里的讨论,一种类型的FormsAuthentication仍然存在。据微软称,

但我也发现Microsoft.Owin.Security.Forms库也不推荐使用(请查看此nuget链接)

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

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]作为全局过滤器。

相关内容

  • 没有找到相关文章

最新更新