CRSF 跨站请求伪造


 

 

protected string cookieName = "";

 

/// 
    /// 创建Toke
    /// 
    /// 
    protected string CreateToken()
    {        
        string gid =  Guid.NewGuid().ToString() + "123546";
        string desString = EncryptedString(gid, DESKey);
              
       
        HttpCookie cookie = Request.Cookies.Get(cookieName);

        if (cookie == null)
        {
            cookie = new HttpCookie(cookieName);
            cookie.Value = desString;
            cookie.Expires = DateTime.Now.AddMinutes(2);
            cookie.HttpOnly = true;
            Response.Cookies.Add(cookie);
        }
        else
        {
            cookie.Value = desString;
            cookie.HttpOnly = true;
            Response.Cookies.Set(cookie);
        }        

        return desString;
    }


 

/// 
    /// 检查token
    /// 
    /// 
    /// 
    protected bool CheckToken(string token)
    {
        bool flag = false;

        try
        {
            HttpCookie cookie = Request.Cookies.Get(GetTokenName());
            if (cookie != null)
            {
                string desString = DecryptedString(cookie.Value, DESKey);
                token = DecryptedString(token, DESKey);
                if (token == desString)
                {
                    flag = true;
                }
            }

        }
        catch (DecryptErrorException ex)
        {
            flag = false;
        }
        catch(SourceIsNullOrEmptyException ex)
        {
            flag = false;
        }
        return flag;
    }


 

 protected string CreateTokenName()
    {
        cookieName = Guid.NewGuid().ToString();
        return cookieName;
    }

    protected string GetTokenName()
    {
        return Utils.GetFormString("TokenName");
    }


 

post验证cookie与提交的token是否一致

string token = Request.From["GUID"];  
 if (!this.CheckToken(token))  
 {  
	return false;  
  }  



 

 
  

 

 
 

你可能感兴趣的:(Asp.Net)