프로그램 자료/ASP.NET

ASP.NET 프로젝트 타입별 CSRF 방어하기

motolies 2014. 8. 27. 13:30

출처http://funnygangstar.tistory.com/170

     

1. ASP.NET MVC

  - @Html.AntiForgeryToken()을 <form> 태그 안쪽에 삽입한다.

  - 컨트롤러 클래스나 액션 메소드를 [ValidateAntiForgeryToken] 어트리뷰트로 선언한다.

     

2. ASP.NET WebForm

- 페이지에 Page.ViewStateUserKey 를 선언한다.

- ftp://106.242.31.204/LUMENS/Site.master.cs

using System;

using System.Collections.Generic;

using System.Security.Claims;

using System.Security.Principal;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class SiteMaster : MasterPage

{

    private const string AntiXsrfTokenKey = "__AntiXsrfToken";

    private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";

    private string _antiXsrfTokenValue;

 

    protected void Page_Init(object sender, EventArgs e)

    {

        // 아래 코드는 XSRF 공격으로부터 보호받는 도움이 됩니다.

        var requestCookie = Request.Cookies[AntiXsrfTokenKey];

        Guid requestCookieGuidValue;

        if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))

        {

            // 쿠키의 Anti-XSRF 토큰 사용

            _antiXsrfTokenValue = requestCookie.Value;

            Page.ViewStateUserKey = _antiXsrfTokenValue;

        }

        else

        {

            // Anti-XSRF 토큰을 생성하여 쿠키에 저장

            _antiXsrfTokenValue = Guid.NewGuid().ToString("N");

            Page.ViewStateUserKey = _antiXsrfTokenValue;

 

            var responseCookie = new HttpCookie(AntiXsrfTokenKey)

            {

                HttpOnly = true,

                Value = _antiXsrfTokenValue

            };

            if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)

            {

                responseCookie.Secure = true;

            }

            Response.Cookies.Set(responseCookie);

        }

 

        Page.PreLoad += master_Page_PreLoad;

    }

 

    protected void master_Page_PreLoad(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            // Anti-XSRF 토큰 설정

            ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;

            ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;

        }

        else

        {

            // Anti-XSRF 토큰 유효성 검사

            if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue

                || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))

            {

                throw new InvalidOperationException("Anti-XSRF 토큰의 유효성을 검사하지 못했습니다.");

            }

        }

    }

 

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

 

    protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)

    {

        Context.GetOwinContext().Authentication.SignOut();

    }

}

 

3. ASP.NET WebAPI

  - 아래 URL 참조

  - http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-(csrf)-attacks

  - http://www.egocube.pe.kr/Translation/Content/asp-net-web-api/201402030001