Asp.net Mvc jqery Ajax Da Csrf Korunma

1

Asp.net mvc ajax işlemlerinde csrf aciğindan nasil korunabiliriz

nisanci53 nisanci53 (13)
8 yıl önce sordu

    Toplam 2 Cevap


    0

    Ajaxda aşağdaki şekilde  yapinca işe yariyor 

    filters den bunu ekliyoruz

    using System;
    using System.Collections.Specialized;
    using System.Net;
    using System.Web;
    using System.Web.Helpers;
    using System.Web.Mvc;
    using System.Web.Routing;
    namespace SORUCEVAP.Filters
    {

     

       
       


        [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
        public class MyValidateAntiForgeryToken : FilterAttribute, IAuthorizationFilter
        {
            

            public void OnAuthorization(AuthorizationContext filterContext)
            {
                string clientToken = filterContext.RequestContext.HttpContext.Request.Headers.Get(KEY_NAME);
                if (clientToken == null)
                {
                    throw new HttpAntiForgeryException(string.Format("Header does not contain {0}", KEY_NAME));
                }

                string serverToken = filterContext.HttpContext.Request.Cookies.Get(KEY_NAME).Value;
                if (serverToken == null)
                {
                    throw new HttpAntiForgeryException(string.Format("Cookies does not contain {0}", KEY_NAME));
                }

                System.Web.Helpers.AntiForgery.Validate(serverToken, clientToken);
            }

            private const string KEY_NAME = "__RequestVerificationToken";

            private class JsonAntiForgeryHttpContextWrapper : HttpContextWrapper
            {
                readonly HttpRequestBase _request;
                public JsonAntiForgeryHttpContextWrapper(HttpContext httpContext)
                    : base(httpContext)
                {
                    _request = new JsonAntiForgeryHttpRequestWrapper(httpContext.Request);
                }

                public override HttpRequestBase Request
                {
                    get
                    {
                        return _request;
                    }
                }
            }

            private class JsonAntiForgeryHttpRequestWrapper : HttpRequestWrapper
            {
                readonly NameValueCollection _form;

                public JsonAntiForgeryHttpRequestWrapper(HttpRequest request)
                    : base(request)
                {
                    _form = new NameValueCollection(request.Form);
                    if (request.Headers["__RequestVerificationToken"] != null)
                    {
                        _form["__RequestVerificationToken"] = request.Headers["__RequestVerificationToken"];
                    }
                }

                public override NameValueCollection Form
                {
                    get
                    {
                        return _form;
                    }
                }
            }
        }

    }

    *******************************************************************************************

    action bu şekilde

            [HttpPost]
            [MyValidateAntiForgeryToken]
            [CustomHandleError]
            public JsonResult Kayit(MODEL.Kullanicilar ekle)
            {
                 
            }

    ******************************************************************************************************

    @{
        ViewBag.Title = "Profil";
        Layout = "~/Views/Shared/Anasayfa.cshtml";
    }

    <script src="~/JS/kayituye.js"></script>

    @model MODEL.Kullanicilar

    $(document).ready(function () {

        $("#Kmesajver").hide();

     
        var antiForgeryToken = $('input[name="__RequestVerificationToken"]').val();
        window.postheaders = {};
        if (antiForgeryToken) {
            window.postheaders["__RequestVerificationToken"] = antiForgeryToken;
        }

     $(document).delegate("#kkayit", "click", function () {

                 
            var Ekle = {

                Kullaniciadi:$("#KullaniciAdi").val(),
                İsim: $("#İsim").val(),
                Email: $("#Email").val(),
                Sifre: $("#Sifre").val(),
                Avatar: $("input[name='avatar']:checked").val(),
                Kontrol: $("#Kontrol").val(),

            };
          
            $("#lyukle").html("<img src='/img/load.gif'>");
            $.ajax({
                url: '/Kullanici/Kayit',
             
                headers: window.postheaders,
                data: JSON.stringify(Ekle),
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (msg) {
                    
                    $(msg).each(function (deger) {
                        if (msg.Durum > 0 || msg.Durum == 1) {

                            $("#rsm").attr('src', '/Kullanici/CaptchaImage?' + new Date().getTime());
                            window.location.href = "/Home/KullaniciKontrol?Mesaj=1";
                          
                        }
                        else {

                            if (msg.Durum == "Tekrar") {
                                $("#lyukle").html("");
                                $("#Kmesajver").show();
                                $("#Kmesajver").html(msg.Kontrol);
                            }

                         else   if (msg.Durum == "İslem") {
                                $("#lyukle").html("");
                                $("#Kmesajver").show();
                                $("#Kmesajver").text("İşlem Yanliş");
                         }
                         else if (msg.Durum == "Kullanimda") {
                             alert("bbbbbb");
                             $("#lyukle").html("");
                             $("#rsm").attr('src', '/Kullanici/CaptchaImage?' + new Date().getTime());
                             $("#Kmesajver").show();
                             $("#Kmesajver").html(msg.Kontrol);
                         }
                            else {
                    
                            }
                        }
                    });
                },
                error: function (e) {
                    $("#rsm").attr('src', '/Kullanici/CaptchaImage?' + new Date().getTime());
                    $("#lyukle").html("");
                    alert(e);
                   
                }
            });
        

        });

    });

     


        @Html.AntiForgeryToken()

     

    <div>
                                    <div >

                                        
                                        <table >
                                            <tbody><tr>
                                                <td >
                                                    isim Ve Soisim:
                                                </td>
                                                    <td >
                                                <input type="text" value="" name="İsim" id="İsim"  />
                                                </td>
                                            </tr>
                                            <tr>
                                                <td >
                                                    Kullaniciadi:
                                                </td>
                                                    <td >
                                                       @Html.TextBoxFor(model => model.KullaniciAdi)@Html.ValidationMessageFor(model=>model.KullaniciAdi)
                                                </td>
                                            </tr>
                                            <tr>
                                                <td >
                                                    Email:
                                                </td>
                                                <td >
                                                
                                                     @Html.TextBoxFor(model => model.Email, new { @class = "qa-form-wide-text" })@Html.ValidationMessageFor(model=>model.Email)
                                                </td>
                                            </tr>
                                            <tr>
                                                <td class="qa-form-wide-label">
                                                    Şifre:
                                                </td>
                                                <td >
                                                   @Html.PasswordFor(model => model.Sifre, new { @class = "qa-form-wide-text" })@Html.ValidationMessageFor(model=>model.Sifre)
                                                </td>
                                            </tr>
                                            
                                            
                                            
                                            <tr>
                                                <td  style="vertical-align:top;">
                                                    Avatar:
                                                </td>
                                                <td >
                                                    <input  name="avatar" type="radio" value="avatar1" checked="" >
                                                     <span style="margin:2px 0; display:inline-block;">
                                                         <img src="~/avatar/avatar1.jpg" width="32" height="32" alt=""></span> Default
                                                    <br>
                                                    <input  name="avatar" type="radio" value="avatar2" > <span style="margin:2px 0; display:inline-block;">
                                                        <img src="~/avatar/avatar2.jpg" width="32" height="32"  alt=""> </span>
                                                
                                                    <br>
                                                    <input  name="avatar" type="radio" value="avatar3" > <span style="margin:2px 0; display:inline-block;">
                                                        <img src="~/avatar/avatar3.jpg" width="32" height="32" class="qa-avatar-image" alt=""> </span>
                                                    <br>
                                                
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td colspan="3" >
                                                        
                                                    
                                                        
                                                        <script>
                                                            function GetCaptcha() {
                                                                $("#rsm").attr('src', '/Kullanici/CaptchaImage?' + new Date().getTime());
                                                            }
    </script>
    <div style="margin-left:300px;" id="resimd">
        <img src="@Url.Action("CaptchaImage")" id="rsm" style="float:left" />
        <input type="text" name="Kontrol" id="Kontrol" value=""  style="width:60px;height:40px;float:left;margin-left:10px;" />
    <input type="button" value="Değiştir" onclick=" return GetCaptcha()"  style="height:40px;margin-left:10px;" /></div>

                                                        <div id="divResult"></div>

                                                    </td>
                                                   
                                                </tr>
                                                
                                                
                                                <tr>
                                                    <td colspan="3" >
                                                        
                                                    <div><div style="float:left;margin-left:300px;"><div id="Kmesajver"  > </div><input  value="Kayit" title="" id="kkayit" type="submit" style="height:60px;width:300px;" ></div><div style="float:left;margin-left:10px;"><div id="lyukle"></div></div></div>   <br /> <br /><br />
                                                        
                                                        
                                                        


                                                    </td>
                                                    <td colspan="3" >
                                                        
                                                  
                                                      
                                                    </td>
                                                </tr>
                                            </tbody></table>
                                            
       

                                    </div>


      
    </div>

    nisanci53 nisanci53 (13)
    8 yıl önce cevaplandı

      0

      Asp.Net MVC 'de AntiForgeryToken özelliği bulunuyor. AntiForgeryToken ile CSRF saldırılarından kurtulabilirsiniz.

      View tarafında:

      <% using(Html.Form("Kullanici", "Guncelle")) { %>
              <%= Html.AntiForgeryToken() %>
              <!-- Form verileri -->
      <% } %>

      Controller tarafında:

      [ValidateAntiForgeryToken]
      public ViewResult Guncelle()
      {
              // AntiForgeryToken gelmeden bu kod çalıştırılmayacaktır.      
      }

       

      murat murat (12492)
      8 yıl önce cevaplandı

      • ajaxda bu şekilde işe yaramiyor form yoksa ne olacak nisanci53 8 yıl önce
      üyelik gerektirir

      Cevap yazabilmek için üye girişi yapmalısınız.

      Eğer uzmanim.net üyesiyseniz giriş yapabilirsiniz: üye girişi yap
      uzmanim.net'e üye olmak çok kolaydır: hemen kayıt ol