GVKun编程网logo

ASP.NET Forms验证(asp.net mvc表单验证)

21

在本文中,我们将详细介绍ASP.NETForms验证的各个方面,并为您提供关于asp.netmvc表单验证的相关解答,同时,我们也将为您带来关于.netMVC中forms验证的使用实例详解、.netM

在本文中,我们将详细介绍ASP.NET Forms验证的各个方面,并为您提供关于asp.net mvc表单验证的相关解答,同时,我们也将为您带来关于.net MVC中forms验证的使用实例详解、.net MVC中使用forms验证详解、ASP.NET 4.5 C#Forms拒绝登录页面的身份验证访问、asp.net 4.5 webforms模型绑定:支持客户端验证?的有用知识。

本文目录一览:

ASP.NET Forms验证(asp.net mvc表单验证)

ASP.NET Forms验证(asp.net mvc表单验证)

/// <summary>
        /// 执行用户登录操作
        /// </summary>
        /// <param name="config">授权配置信息</param>
        /// <param name="userData">与登录名相关的用户信息</param>
        /// <param name="expiration">登录Cookie的过期时间,单位:分钟,默认120分钟。</param>
        public static void SignIn(IovAuthConfig config, UserInfo userData, int expiration = 120)
        {
            if (config == null)
                throw new ArgumentNullException("config");
            if (userData == null)
                throw new ArgumentNullException("userData");
            if(string.IsNullOrWhiteSpace(config.AppID))
                throw new ArgumentNullException("AppID");
            // 1. 把需要保存的用户数据转成一个字符串。
            string data = null;
            if (userData != null)
                data = JsonHelper.Serialize(userData);


            // 2. 创建一个FormsAuthenticationTicket,它包含登录名以及额外的用户数据。
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                2, userData.LoginID, DateTime.Now, DateTime.Now.AddDays(1), true, data);


            // 3. 加密Ticket,变成一个加密的字符串。
            string cookieValue = FormsAuthentication.Encrypt(ticket);


            // 4. 根据加密结果创建登录Cookie
            HttpCookie cookie = new HttpCookie(config.AppID, cookieValue);
            cookie.HttpOnly = true;
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Domain = FormsAuthentication.CookieDomain;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            //if (expiration > 0)
            //默认过期时间:120分钟
            cookie.Expires = DateTime.Now.AddMinutes(expiration == 0 ? 120 : expiration);

            HttpContext context = HttpContext.Current;
            if (context == null)
                throw new InvalidOperationException();

            // 5. 写登录Cookie
            context.Response.Cookies.Remove(cookie.Name);
            context.Response.Cookies.Add(cookie);
        }

  web.config同时需要修改两个地方,如下:

<system.web>
     <authentication mode="Forms">
      <forms name="IOV.Test" loginUrl="/" protection="All" timeout="43200" path="/" domain="" requireSSL="false" slidingExpiration="true" />
    </authentication>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>

  

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"></modules>
  </system.webServer>

  获取已登录用户信息:

/// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <param name="context">当前Http请求上下文</param>
        /// <returns></returns>
        public static UserInfo TryGetUserInfo(HttpContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            // 1. 读登录Cookie
            HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (cookie == null || string.IsNullOrEmpty(cookie.Value))
                return null;

            try
            {
                UserInfo userData = null;
                // 2. 解密Cookie值,获取FormsAuthenticationTicket对象
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

                if (ticket != null && string.IsNullOrEmpty(ticket.UserData) == false)
                    // 3. 还原用户数据
                    userData = JsonHelper.Desrialize<UserInfo>(ticket.UserData);

                return userData;
            }
            catch { /* 有异常也不要抛出,防止攻击者试探。 */ }
            return null;
        }

  

.net MVC中forms验证的使用实例详解

.net MVC中forms验证的使用实例详解

这篇文章主要为大家详细介绍了.net mvc中使用forms验证的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

.net MVC中使用forms验证,供大家参考,具体内容如下

文件夹的分部是这样子的

首先在Web.config中设置

authentication和authorization 节点


 <system.web>
  <authentication mode="Forms">
   <forms loginUrl="~/Login/Index" timeout="2880" defaultUrl="~/Home/Index"/>
  </authentication>
  <anonymousIdentification enabled="true"/>
  <authorization>
   <deny users="?"/> <!--拒绝匿名访问-->
  </authorization>
  <compilation debug="true" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5" />
  <httpModules>
   <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
  </httpModules>
 </system.web>
登录后复制

如果在Login文件夹还有不需要匿名访问,或者在LoginController中除了登陆还有方法可以匿名访问,

那么我们需要在加上这一个节点


 <location path="Login"> <!--这里的意思就是LoginController下的方法可以匿名访问-->
  <system.web>
   <authorization>
    <allow users="*" /> <!--允许匿名访问-->
   </authorization>
  </system.web>
 </location>
登录后复制

登陆的方法贴出一部分代码,仅供参考


 public bool ValidateUser(LoginVO model)
    {
      string encodePassword = MD5(model.PassWord);//加密
      string sql =
        "select * from User_Users where (UserName=@UserName or JobNumber=@JobNumber) and PassWord=@PassWord";
      var user = Context.Data.Query<UsersPO>(sql,
        new {UserName = model.LoginName, JobNumber = model.LoginName, PassWord = encodePassword}).SingleOrDefault();
      if (user == null) return false;
      DateTime expiration = model.IsRememberLogin //是否记住密码
        ? DateTime.Now.AddDays(14)
        : DateTime.Now.Add(FormsAuthentication.Timeout);
      var ticket=new FormsAuthenticationTicket(
        1,//指定版本号:可随意指定
        user.UserName,//登录用户名:对应 Web.config 中 <allow users="Admin" … /> 的 users 属性
        DateTime.Now, //发布时间
        expiration,//失效时间
        true,//是否为持久 Cookie
        user.UserId.ToString(), //用户数据:可用 ((System.Web.Security.FormsIdentity)(HttpContext.Current.User.Identity)).Ticket.UserData 获取
        FormsAuthentication.FormsCookiePath //指定 Cookie 为 Web.config 中 <forms path="/" … /> path 属性,不指定则默认为“/”
        );
      var encryptedTicket = FormsAuthentication.Encrypt(ticket);
      if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
      {
        HttpContext.Current.Request.Cookies.Remove(FormsAuthentication.FormsCookieName);
      }
      var loginIdentify=new HttpCookie(FormsAuthentication.FormsCookieName);
      if (model.IsRememberLogin)
      {
        loginIdentify.Expires = DateTime.Now.AddDays(7);
      }
      loginIdentify.Value = encryptedTicket;
      HttpContext.Current.Response.AppendCookie(loginIdentify);//添加Cookie
      return true;
    }

    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="str"></param>
    /// <param name="encoding"></param>
    /// <param name="toUpper"></param>
    /// <param name="isReverse"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    private string MD5(string str, Encoding encoding=null, int count = 1)
    {
      if (encoding == null)
      {
        encoding = Encoding.Default;
      }
      var bytes = new MD5CryptoServiceProvider().ComputeHash(encoding.GetBytes(str));
      var md5 = string.Empty;
      for (int i = 0; i < bytes.Length; i++)
      {
        md5 += bytes[i].ToString("x").PadLeft(2, &#39;0&#39;);
      }     
      if (count <= 1) { return md5; }
      return MD5(md5, encoding, --count);
    }
登录后复制

以上就是.net MVC中forms验证的使用实例详解的详细内容,更多请关注php中文网其它相关文章!

.net MVC中使用forms验证详解

.net MVC中使用forms验证详解

.net MVC中使用forms验证,供大家参考,具体内容如下

文件夹的分部是这样子的

首先在Web.config中设置

authentication和authorization 节点

 <system.web>
  <authentication mode="Forms">
   <forms loginUrl="~/Login/Index" timeout="2880" defaultUrl="~/Home/Index"/>
  </authentication>
  <anonymousIdentification enabled="true"/>
  <authorization>
   <deny users="?"/> <!--拒绝匿名访问-->
  </authorization>
  <compilation debug="true" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5" />
  <httpModules>
   <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
  </httpModules>
 </system.web>

如果在Login文件夹还有不需要匿名访问,或者在LoginController中除了登陆还有方法可以匿名访问,

那么我们需要在加上这一个节点

 <location path="Login"> <!--这里的意思就是LoginController下的方法可以匿名访问-->
  <system.web>
   <authorization>
    <allow users="*" /> <!--允许匿名访问-->
   </authorization>
  </system.web>
 </location>

登陆的方法贴出一部分代码,仅供参考

 public bool ValidateUser(LoginVO model)
    {
      string encodePassword = MD5(model.PassWord);//加密
      string sql =
        "select * from User_Users where (UserName=@UserName or JobNumber=@JobNumber) and PassWord=@PassWord";
      var user = Context.Data.Query<UsersPO>(sql,
        new {UserName = model.LoginName, JobNumber = model.LoginName, PassWord = encodePassword}).SingleOrDefault();
      if (user == null) return false;
      DateTime expiration = model.IsRememberLogin //是否记住密码
        ? DateTime.Now.AddDays(14)
        : DateTime.Now.Add(FormsAuthentication.Timeout);
      var ticket=new FormsAuthenticationTicket(
        1,//指定版本号:可随意指定
        user.UserName,//登录用户名:对应 Web.config 中 <allow users="Admin" … /> 的 users 属性
        DateTime.Now, //发布时间
        expiration,//失效时间
        true,//是否为持久 Cookie
        user.UserId.ToString(), //用户数据:可用 ((System.Web.Security.FormsIdentity)(HttpContext.Current.User.Identity)).Ticket.UserData 获取
        FormsAuthentication.FormsCookiePath //指定 Cookie 为 Web.config 中 <forms path="/" … /> path 属性,不指定则默认为“/”
        );
      var encryptedTicket = FormsAuthentication.Encrypt(ticket);
      if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
      {
        HttpContext.Current.Request.Cookies.Remove(FormsAuthentication.FormsCookieName);
      }
      var loginIdentify=new HttpCookie(FormsAuthentication.FormsCookieName);
      if (model.IsRememberLogin)
      {
        loginIdentify.Expires = DateTime.Now.AddDays(7);
      }
      loginIdentify.Value = encryptedTicket;
      HttpContext.Current.Response.AppendCookie(loginIdentify);//添加Cookie
      return true;
    }

    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="str"></param>
    /// <param name="encoding"></param>
    /// <param name="toUpper"></param>
    /// <param name="isReverse"></param>
    /// <param name="count"></param>
    /// <returns></returns>
    private string MD5(string str, Encoding encoding=null, int count = 1)
    {
      if (encoding == null)
      {
        encoding = Encoding.Default;
      }
      var bytes = new MD5CryptoServiceProvider().ComputeHash(encoding.GetBytes(str));
      var md5 = string.Empty;
      for (int i = 0; i < bytes.Length; i++)
      {
        md5 += bytes[i].ToString("x").PadLeft(2, ''0'');
      }     
      if (count <= 1) { return md5; }
      return MD5(md5, encoding, --count);
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

您可能感兴趣的文章:
  • .net core利用orm如何操作mysql数据库详解
  • .net MVC使用IPrincipal进行Form登录即权限验证(3)
  • ASP.NET MVC下Ajax.BeginForm方式无刷新提交表单实例
  • .net WINFORM的GDI双缓冲的实现方法
  • Asp.net webForm设置允许表单提交Html的方法
  • Asp.net mvc验证用户登录之Forms实现详解
  • asp.net mvc中Forms身份验证身份验证流程
  • asp.net core标签助手的高级用法TagHelper+Form
  • 深入理解Asp.Net中WebForm的生命周期
  • .NET Orm性能测试分析

ASP.NET 4.5 C#Forms拒绝登录页面的身份验证访问

ASP.NET 4.5 C#Forms拒绝登录页面的身份验证访问

我已经找到了一些帖子,但我似乎找不到合适的解决方案:

我有一个.net 4.0 Web应用程序,它使用Forms身份验证非常好.现在,我想在4.5中的新项目中实现相同的功能,但是当我进入未经授权的部分时,我在登录页面上不断收到401.2(访问被拒绝)错误.

应用程序重定向正确(以mvc方式,在我的页面中没有.aspx),但在登录页面上,由于服务器配置,我不断收到我未经授权查看此页面的错误.

然后我尝试了microsoft的演示,它支持框架4.5,但它仍然不起作用.

这是我的一般web.config部分:

<authentication mode="Forms">
  <forms loginUrl="/admin/Login.aspx" />
</authentication>

这是我的文件夹中的web.config,我希望保护其免受未经授权的用户的攻击:

<system.web>
     <authorization>
      <deny users="?" />
     </authorization>
    </system.web>

当我设置allow users =“*”时,应用程序工作正常,我可以进入每一页.
然后我认为它可能与我的表单身份验证中的mvc方法有关,但这似乎不是问题,我也尝试过Rick Strahl的这个修复程序,但这没有帮助. (link)

有任何想法吗?

编辑当我将login.aspx的位置更改为受保护区域外的文件夹时,我得到了正确的重定向,但我想将login.aspx页面保留在受保护的文件夹中,就像我之前做的那样. visual studio自动允许访问loginUrl =“”,不是吗?

解决方法

就我而言,问题与Visual Studio 2017有关.我的任务是将旧的.net网站转换为Web应用程序项目.作为任务的一部分,我创建了一个新的VS2017 Web应用程序项目,从旧的Web站点代码库中复制到所需的文件中,运行转换为Web应用程序,添加名称空间等,并且大部分时间都可以运行.

该应用程序使用表单身份验证和webconfig表单标记引用LocalLogin.aspx页面,但我会在浏览器中获得“访问被拒绝”消息,并且永远无法访问LocalLogin.aspx页面.经过大量的谷歌搜索,我发现了这个:

“Visual Studio 2017将自动将名为Microsoft.AspNet.FriendlyUrls的NuGet包添加到您的网站或Web应用程序项目.由于此包,表单身份验证将无法工作,甚至登录页面也不会呈现多次.”转到此主题以获取更多信息:

Login Page in ASP.NET application with FormsAuthentication access denied

在查看该线程中可能的解决方案之后,我选择删除友好的URL引用(Microsoft.AspNet.FriendlyUrls),并将扩展保留在web.config forms标记中的loginUrl和defaultUrl元素上.顺便说一句,解决方案中没有添加NuGet包,只是参考.我删除了引用,还必须注释掉routeconfig调用和方法.

在这之后,它仍然在浏览器中给出了“访问被拒绝”消息,但事实证明我还需要从浏览器中删除缓存的永久301重定向到友好URL,这是通过使用FriendlyUrls组件创建的首先.

我用Google搜索“从浏览器缓存中删除301重定向”,然后执行以下操作:

“要清除永久重定向,请转到chrome:// net-internals.在顶部红色状态栏的右侧,单击向下箭头▼打开下拉菜单,然后在”工具“组下,选择“清除缓存”.从版本48开始,这是唯一能够清除缓存301的东西.“

How long do browsers cache HTTP 301s?

现在,一切都很顺利,希望我的一些头发可以恢复!

asp.net 4.5 webforms模型绑定:支持客户端验证?

asp.net 4.5 webforms模型绑定:支持客户端验证?

我是使用数据注释的asp.net 4.5 webforms模型绑定的忠实粉丝.

ASCX:

<asp:FormView ItemType="Contact" runat="server" DefaultMode="Edit" 
     SelectMethod="GetContact" UpdateMethod="SaveContact">
        <EditItemTemplate>   

              <asp:ValidationSummary runat="server" ID="valSum" />

              Firstname: <asp:TextBox  runat="server"  ID="txtFirstname" Text='<%#: BindItem.Firstname %>' /> 


              Lastname: <asp:TextBox  runat="server"  ID="txtLastname" Text='<%#: BindItem.Lastname %>' />

              Email:  <asp:TextBox  runat="server"  ID="txtEmail" Text='<%#: BindItem.Email %>' />     

              <asp:Button ID="Button1"  runat="server" Text="Save" CommandName="Update" />
        </EditItemTemplate>   
    </asp:FormView>

的.cs:

public void SaveContact(Contact viewmodel)
    {
        if (!Page.ModelState.IsValid)
        {
            return;
        }            
    }              

    public Contact GetContact() 
    {
         return new Contact();
    }

模型:

public class Contact
    {
        [required]
        [StringLength(10,ErrorMessage="{1} tis te lang")]   
        public string Firstname { get; set; }

        [required]
        [StringLength(10)]
        public string Lastname { get; set; }

        [required]
        [EmailAddress]       
        public string Email { get; set; }

    }

题:

客户端验证是否支持MVC中的Webforms开箱即用?
或者我们应该依赖第三方库(DAValidation).是否可以将Html.EnableClientValidation()的优点移植到webforms?

问候,

巴特

解决方法

正如我们在ASP.NET WebForms项目中发现的那样,对于客户端验证,模型的验证属性没有全面有用的重用.

例如,具有各种属性(如姓名,电子邮件,生日等)的联系人数据模型并不总是以相同的方式使用.有时它可能有一些必填字段,有时不会,甚至所需的输入数据可能在应用程序的不同点有所不同.

因此,在我们的项目中,我们使用客户端验证实现和模型属性.

我们应用的一般想法是:

>在客户端,我们希望尽可能具体,避免不必要的回发,并为用户提供即时,具体的响应.
>在服务器端,我们应用模型属性以及更多数据库和面向业务的验证规则,并且不是那么具体.另外,如果需要,当某些字段相互依赖时,会发生一些“属性间”验证.

对于客户端,我们选择了jQuery Validate Plugin(http://jqueryvalidation.org/).

我们甚至构建了自己的一组控件(源自内置的WebControls),它们呈现各种(甚至是一些自定义的)数据规则.

今天关于ASP.NET Forms验证asp.net mvc表单验证的讲解已经结束,谢谢您的阅读,如果想了解更多关于.net MVC中forms验证的使用实例详解、.net MVC中使用forms验证详解、ASP.NET 4.5 C#Forms拒绝登录页面的身份验证访问、asp.net 4.5 webforms模型绑定:支持客户端验证?的相关知识,请在本站搜索。

本文标签: