Form认证的几点说明

有的页面需要用户认证之后才可以进入,通常都是在Filter的OnActionExecuting方法中我们需要获取当前用户。有两种情况不必登录:1.用户是登录的,也就是认证过的。2.用户上次登录了,但没有退出就关闭了页面,且还Cookie还没有过期。这个时候

Request.IsAuthenticated=true

所以用户不必再登录。

如果用户退出,也就是调用SignOut()

 public void SignOut()
        {
            _cachedUser = null;
            FormsAuthentication.SignOut();
        }

这个时候获取不到认证用户。

Filter就会让用户返回到登录页面。

 var user = WorkContext.CurrentUser;
if (user == null)
 {
    filterContext.Result = new RedirectResult("~/Account/Logon?returnUrl=" + returnUrl);
  }

另外,在Ninject中无法注入HttpContextBase,但可以讲其换成属性。

   public HttpContextBase HttpContext
        {
            get { return new HttpContextWrapper(System.Web.HttpContext.Current); }
        }

而对于Filter可以属性注入。

  [Inject]
  public IAuthenticationService AuthenticationService { get; set; }

LoginValidAttribute 源码:

 public class LoginValidAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 转到管理员登陆的界面
        /// </summary>
        private bool _isAdmin;

        public LoginValidAttribute(bool isadmin = false)
        {
            _isAdmin = isadmin;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var contr = filterContext.RouteData.Values["controller"].ToString();
            var action = filterContext.RouteData.Values["action"].ToString();
            var parmdatas = filterContext.ActionParameters;
            var parms = "?";
            var i = 0;
            var count = parmdatas.Count;
            foreach (var parmdata in parmdatas)
            {
                i++;
                if (i <= count - 1)
                {
                    parms += parmdata.Key + "=" + parmdata.Value + "&";
                }
                else
                {
                    parms += parmdata.Key + "=" + parmdata.Value;

                }
            }
            if (count == 0) parms = "";
            var returnUrl = string.Format("~/{0}/{1}{2}", contr, action, parms);
            returnUrl = UrlHelper.GenerateContentUrl(returnUrl, filterContext.HttpContext);

            var user = WorkContext.CurrentUser;
            if (user == null)
            {
                filterContext.Result = new RedirectResult("~/Account/Logon?returnUrl=" + returnUrl);
            }

            // 如果已经登录 但不是角色,就需要跳转到只是页面 提示是管理员才能登录

        }

        [Inject]
        public IWorkContext WorkContext { get; set; }

    }

WebWorkContext:

  public class WebWorkContext : IWorkContext
    {
        #region Const

        #endregion

          #region Fields

        private readonly IUserService _userService;
        private User _cachedUser;

        #endregion

        public WebWorkContext( IUserService userService )
        {
            _userService = userService;
        }

        #region Utilities

        protected virtual HttpCookie GetUserCookie()
        {
            if (HttpContext == null || HttpContext.Request == null)
                return null;

            return HttpContext.Request.Cookies[PortalConfig.UserCookieName];
        }

        protected virtual void SetUserCookie(Guid customerGuid)
        {
            if (HttpContext != null && HttpContext.Response != null)
            {
                var cookie = new HttpCookie(PortalConfig.UserCookieName);
                cookie.HttpOnly = true;
                cookie.Value = customerGuid.ToString();
                if (customerGuid == Guid.Empty)
                {
                    cookie.Expires = DateTime.Now.AddMonths(-1);
                }
                else
                {
                    int cookieExpires = 24 * 30; //TODO make configurable
                    cookie.Expires = DateTime.Now.AddHours(cookieExpires);
                }

                HttpContext.Response.Cookies.Remove(PortalConfig.UserCookieName);
                HttpContext.Response.Cookies.Add(cookie);
            }
        }

        #endregion

        public virtual User CurrentUser
        {
            get
            {

                User customer = AuthenticationService.GetAuthenticatedCustomer(); ;

                //load guest customer
                if (customer == null || customer.Deleted || !customer.Active)
                {
                    var customerCookie = GetUserCookie();
                    if (customerCookie != null && !String.IsNullOrEmpty(customerCookie.Value))
                    {
                        Guid customerGuid;
                        if (Guid.TryParse(customerCookie.Value, out customerGuid))
                        {
                            var customerByCookie = _userService.GetUserByGuid(customerGuid);
                            if (customerByCookie != null &&IsCurrentUser)
                                //this customer (from cookie) should not be registered
                                //!customerByCookie.IsRegistered())
                                customer = customerByCookie;
                        }
                    }
                }

                //validation
                if (customer!=null&&!customer.Deleted && customer.Active)
                {
                    SetUserCookie(customer.UserGuid);
                }

                return customer;
                ;
            }
            set
            {
                SetUserCookie(value.UserGuid);
                _cachedUser = value;
            }
        }

        public User OriginalUserIfImpersonated { get; private set; }
        public bool IsAdmin { get; set; }
        public bool IsCurrentUser {
            get { return AuthenticationService.IsCurrentUser; }
        }

        public HttpContextBase HttpContext
        {
            get { return new HttpContextWrapper(System.Web.HttpContext.Current); }
        }

        [Inject]
        public IAuthenticationService AuthenticationService { get; set; }
    }

FormsAuthenticationService:

 public class FormsAuthenticationService : IAuthenticationService
    {
        private readonly IUserService _userService;
        private readonly TimeSpan _expirationTimeSpan;

        private User _cachedUser;

        public FormsAuthenticationService(IUserService userService)
        {
            _userService = userService;
            _expirationTimeSpan = FormsAuthentication.Timeout;
        }

        public void SignIn(User user, bool createPersistentCookie)
        {
            var now = DateTime.UtcNow.ToLocalTime();
            var ticket = new FormsAuthenticationTicket(1, user.Username, now, now.Add(_expirationTimeSpan),
                createPersistentCookie, user.Username, FormsAuthentication.FormsCookiePath);
            var encryptedTicket = FormsAuthentication.Encrypt(ticket);
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) {HttpOnly = true};
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }
            HttpContext.Response.Cookies.Add(cookie);
            //nop源码中没有这一句,务必保证webconfig中的认证是form的。
           // FormsAuthentication.SetAuthCookie(user.Username, createPersistentCookie);
            _cachedUser = user;
        }

        public void SignOut()
        {
            _cachedUser = null;
            FormsAuthentication.SignOut();
        }

        public User GetAuthenticatedCustomer()
        {
            if (_cachedUser != null) return _cachedUser;
            if (HttpContext == null || HttpContext.Request == null || !HttpContext.Request.IsAuthenticated ||
                !(HttpContext.User.Identity is FormsIdentity))
            {
                return null;
            }
            var formsIdentity = (FormsIdentity)HttpContext.User.Identity;
            var user = GetAuthenticatedUserFromTicket(formsIdentity.Ticket);
            if (user != null && user.Active && !user.Deleted )//&& user.IsRegistered()
                _cachedUser = user;
            return _cachedUser;
        }

        public bool IsCurrentUser
        {
            get { return GetAuthenticatedCustomer() != null; }
        }

        public virtual User GetAuthenticatedUserFromTicket(FormsAuthenticationTicket ticket)
        {
            if (ticket == null)
                throw new ArgumentNullException("ticket");

            var usernameOrEmail = ticket.Name;

            if (String.IsNullOrWhiteSpace(usernameOrEmail))
                return null;

            var user = _userService.GetUserByUsername(usernameOrEmail);

            return user;
        }

        public HttpContextBase HttpContext
        {
            get { return new HttpContextWrapper(System.Web.HttpContext.Current); }
        }
    }

时间: 2024-07-30 13:43:27

Form认证的几点说明的相关文章

sharepoint:基于AD的FORM认证

//来源:http://www.cnblogs.com/jindahao/archive/2012/05/07/2487351.html 需求: 1. 认证要基于AD 2. 登入方式要页面的方式(form) 3. 添加自定义验证逻辑 方案: 根据需求可以很快明白,实际就是个“基于AD的FORM认证”.具体步骤如下: 1. 修改web.config 添加“<connectionStrings>” <connectionStrings> <add name="ADCon

MVC用户登陆验证及权限检查(Form认证)

1.配置Web.conf,使用Form认证方式 <system.web> <authentication mode="None" /> <compilation debug="true" targetFramework="4.6.1" /> <httpRuntime targetFramework="4.6.1" /> <authentication mode="

SharePoint 2013 配置基于AD的Form认证

前 言 配置SharePoint 2013基于AD的Form认证,主要有三步: 1. 修改管理中心的web.config: 2. 修改STS Application的web.config: 3. 修改Web应用程序的web.config并开启FBA: 首先,修改CA的web.config,一般在不知道端口号的时候(因为创建CA的时候,即使我们修改了端口号,创建后也会使用默认的那个,但是访问却使用我们填写的那个),我们选择在IIS中找到CA文件路径,如下图: 通常我们应该先进行web.config

Asp.Net实现FORM认证的一些使用技巧(必看篇)

最近因为项目代码重构需要重新整理用户登录和权限控制的部分,现有的代码大体是参照了.NET的FORM认证,并结合了PORTAL KITS的登录控制,代码比较啰嗦,可维护性比较差.于是有了以下的几个需求(大多数系统应该都会碰到): 1.用.NET自带的FORM认证来实现安全登录 2.登录后需要记录登录用户的基本信息,方便所有页面调用 3.记录本机登录状态,短时间关闭窗口后不用重新登录 4.权限控制和代码的文件夹结构相呼应,即按角色允许访问不同的目录 5.权限控制有可能需要细化到每一个页面,即按角色允

MVC4.0 使用Form认证,自定义登录页面路径Account/Login

使用MVC4.0的时候,一般遇到会员登录.注册功能,我们都会使用Form认证,给需要身份验证的Action进行授权(需要登录后才能访问的Action添加[Authorize]属性标签),登录.注册的时候给用户添加票据信息,以便可以访问需要身份验证的Action操作或者视图 同时在web.config中我们会看到这样的配置代码,当我们修改loginUrl的值时,会发现当我们未被授权但要访问需要身份验证的视图时,依然会被强制返回Account/Login页面 <authentication mode

Asp.Net实现FORM认证的一些使用技巧

原文转发:http://www.cnblogs.com/Showshare/archive/2010/07/09/1772886.html 最近因为项目代码重构需要重新整理用户登录和权限控制的部分,现有的代码大体是参照了.NET的FORM认证,并结合了PORTAL KITS的登录控制,代码比较啰嗦,可维护性比较差.于是有了以下的几个需求(大多数系统应该都会碰到): 用.NET自带的FORM认证来实现安全登录 登录后需要记录登录用户的基本信息,方便所有页面调用 记录本机登录状态,短时间关闭窗口后不

Sharepoint 2010配置form认证方式(SQL账号)

Sharepoint 2010配置form认证方式(SQL账号) 一.准备工作: 1.首先我们创建我们form认证中所需要的数据库. 找到aspnet_regsql.exe,一般在C:\Windows\Microsoft.NET下,根据操作系统进行选择.因为本人是win2008 R2x64,所以打开目录为C:\Windows\Microsoft.NET\Framework64\v2.0.50727 2.双击运行后,点击下一步,然后选择为应用程序配置sql server,如图: 3.填写,服务器名

案例演示按&quot;角色&quot;的form认证实现过程

参考了一些资料,将按角色的form认证的步骤和实现总结如下: 第一步:建立如图结构: 第二步:在根目录的web.config中添加authentication和authorization节点,并进行设置 第三步:在login.aspx.cs内为登陆页面添加登陆按钮事件 第四步:在global.asax页面中添加Application_AuthenticateRequest事件,并写入代码 原理文章总结:http://blog.csdn.net/goodshot/article/details/5

浅谈MVC Form认证

简单的谈一下MVC的Form认证. 在做MVC项目时,用户登录认证需要选用Form认证时,我们该怎么做呢?下面我们来简单给大家说一下. 首先说一下步骤 1.用户登录时,如果校验用户名密码通过后,需要调用FormsAuthentication.SetAuthCookie()这个方法. 2.用户退出时,需要调用FormsAuthentication.SignOut();方法 3.在配置文件web.config中,system.web 节点下, 配置<authentication  mode="

Asp.Net 之 使用Form认证实现用户登录 (LoginView的使用)

1. 创建一个WebSite,新建一个页面命名为SignIn.aspx,然后在页面中添加如下的代码 <div class="div_logView"> <asp:LoginView ID="loginView" runat="server" EnableViewState="false"> <AnonymousTemplate> <div style="margin:14px