如何在ASP.NET C#中防止CSRF攻击?当我使用VS10时

时间:2019-01-10 13:06:22

标签: asp.net

protected override void OnInit(EventArgs e)
{
    if (!this.Page.EnableViewStateMac)
    {
        throw new Exception("MAC is not enabled for the page and the view state is therefore vulnerable to tampering.");
    }
    ViewStateUserKey = Session.SessionID;
    base.OnInit(e);
}

private const string AntiXsrfToenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNmeKey = "__AntiXsrfUserName";
private string _antiXsrfToenValue;

protected void Page_Init(object sender, EventArgs e)
{
    // The below code helps to protect from XSRF attacks  
    var requestCookie = Request.Cookies[AntiXsrfToenKey];
    Guid requestCookieGuidValue;
    if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
    {
        // Use the Anti-XSRF token from the cookie  
        _antiXsrfToenValue = requestCookie.Value;
        Page.ViewStateUserKey = _antiXsrfToenValue;
    }
    else
    {
        // Create new Anti-XSRF token and assign to the cookie  
        _antiXsrfToenValue = Guid.NewGuid().ToString("N");
        Page.ViewStateUserKey = _antiXsrfToenValue;

        var responseCookie = new HttpCookie(AntiXsrfToenKey)
        {
            HttpOnly = true,
            Value = _antiXsrfToenValue
        };
        Response.Cookies.Set(responseCookie);
    }
}  

0 个答案:

没有答案