zoukankan      html  css  js  c++  java
  • AJAX安全-Session做Token

    个人思路,请大神看到了指点

    个人理解token是防止扫号机或者恶意注册、恶意发表灌水,有些JS写的token算法,也会被抓出来被利用,个人感觉还是用会过期的Session做token更好,服务器存储,加载到客户端页面,然后进行对比

    index.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
         <script type="text/javascript" src="jquery.js"></script>
         <script>
             function submist() {
                 if ($("#HDToken").val() != null) {
                     var JsonData = {
                         Token: $("#HDToken").val(),
                         sid: Math.random()
                     };
    
                     $.ajax({
                         type: "post",
                         url: "index.ashx",
                         dataType: "json",
                         data: JsonData,
                         success: function (data) {
                             if (data[0].status == 'success') {
    
                                 alert("成功" + data[0].message);
    
    
                             }
                             else {
                                 alert("失败" + data[0].message);
    
    
                             }
                         },
                         error: function (data, status, e) {
                             alert("系统错误" + status + "|" + data[0].message);
    
                         }
                     });
                 }
                 else {
                     alert("回话过期,重新刷新页面");
                     return;
                 }
             }
            
         
         </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        <input id="HDToken" type="hidden"  runat="server" />
            <input id="Button1" type="button" value="提交"  onclick="submist()"/>
            <asp:Button ID="Button2" runat="server" Text="清除" onclick="Button2_Click" />
            </div>
        </form>
    </body>
    </html>

    index.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
            if (!IsPostBack)
            {
                string Token = "";
                if (Session["Token"] == null)
                {
                    Session["Token"] = DateTime.Now.ToString();
                    Token = Session["Token"].ToString();
                    HDToken.Value = FormsAuthentication.HashPasswordForStoringInConfigFile(Token, "md5").ToLower();//MD5加密后赋值给隐藏域
                    //Response.Write(HDToken.Value);
    
                }
                else
                {
                        Token = Session["Token"].ToString();
                        HDToken.Value = FormsAuthentication.HashPasswordForStoringInConfigFile(Token, "md5").ToLower();
                       // Response.Write(HDToken.Value);
    
                        //以下为回话过期,可以放在Global.asax 做定时器
                        TimeSpan span=DateTime.Now.Subtract(Convert.ToDateTime(Session["Token"]));
                        int min = span.Minutes + 1;
                        if (min > 1)
                        {
                            Session.Remove("Token");//时间大于1分钟,移除
                        }
                }
                 
            }
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            Session.Abandon();
        }
    }

    index.ashx

    <%@ WebHandler Language="C#" Class="index" %>
    
    using System;
    using System.Web;
    using System.Web.Security;
    using System.Web.SessionState;
    
    public class index : IHttpHandler, IRequiresSessionState
    {
    
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string Token = context.Request["Token"];//获得隐藏域的值
            if (context.Session["Token"] != null)
            {
                
                if (FormsAuthentication.HashPasswordForStoringInConfigFile(context.Session["Token"].ToString(), "md5").ToLower() == Token)
                {
                    context.Response.Write("[{"message":"成功","status":"success"}]");
                    context.Response.End();
                    return;
                }
                else
                {
                    context.Response.Write("[{"message":"失败","status":"error"}]");
                    context.Response.End();
                    return;
                }
            }
            else
            {
                context.Response.Write("[{"message":"过期","status":"error"}]");
                context.Response.End();
                return;
            }
            
        }
     
        public bool IsReusable {
            get {
                return false;
            }
        }
    
    }

     另一种方法,在请求头部加入token

        if (!IsPostBack)
        {
                    ///生成 Token
                    string Token = new Random().NextDouble().ToString();
                    Session["token"] = Token;
                    System.Web.UI.HtmlControls.HtmlGenericControl script = new System.Web.UI.HtmlControls.HtmlGenericControl("script");
                    script.Attributes.Add("type", "text/javascript");
                    script.InnerHtml = @"
                    $.ajaxSetup({
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader(""token"", """ + Token + @""");
                    }
                });
                 ";
                    Page.Header.Controls.Add(script);
         }

    在请求结果页面直接获得string Token = context.Request.Headers["token"];

  • 相关阅读:
    实例讲解Springboot以Repository方式整合Redis
    Spark join 源码跟读记录
    数理统计与参数估计杂记
    常见的距离算法和相似度(相关系数)计算方法
    生成模型(Generative Model)与判别模型(Discriminative Model)
    Java 积累复习用
    RangePartitioner 实现简记
    Spark常见问题汇总
    2016年终总结
    学习资料库
  • 原文地址:https://www.cnblogs.com/qigege/p/4828289.html
Copyright © 2011-2022 走看看