Preface

CSRF(Cross-site request forgery Cross-site request forgery , Also known as “One Click Attack” perhaps Session Riding, Commonly abbreviated as CSRF perhaps XSRF, Is a malicious use of the site . This article USES the ASP.NET MVC Provided AntiForgery Conduct safety verification

application

One 、 Customize FilterAttribute filter

 /// <summary>
/// Response return value
/// </summary>
public class TActionResult
{
/// <summary>
/// Create a return value
/// </summary>
/// <param name="content"> Return value </param>
/// <returns></returns>
public static ActionResult CreateResult(string content)
{
var contentResult = new ContentResult
{
Content = content,
ContentEncoding = Encoding.UTF8
};
return contentResult;
}
}
 public class TValidateAntiForgeryTokenAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
try
{
var request = filterContext.HttpContext.Request;
if (request.HttpMethod == WebRequestMethods.Http.Post)
{
if (request.IsAjaxRequest())
{
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = antiForgeryCookie != null
? antiForgeryCookie.Value
: null;
// from cookies and Headers in Verify the security label
// obtain token
var token = request.Headers["__RequestVerificationToken"];
// verification token
AntiForgery.Validate(cookieValue, token);
}
else
{
new ValidateAntiForgeryTokenAttribute()
.OnAuthorization(filterContext);
}
}
}
catch
{
filterContext.Result = TActionResult.CreateResult(" Can't verify Token!");
}
}
}

Two 、 View

 @Html.AntiForgeryToken()

3、 ... and 、HomeController

 [TValidateAntiForgeryToken]
public string Test()
{
return "Token Verification passed !";
}

Four 、Jquery Use Ajax Send the request

1. Set global request header header

 $.ajaxSetup({
beforeSend: function (xhr) {
// You can set custom headers
xhr.setRequestHeader('__RequestVerificationToken', $("input[name=__RequestVerificationToken][type=hidden]").val()); }
})

2.ajax request

 $.post("/home/test",function(msg) {
alert(msg);
})

5、 ... and 、 remarks :

1. If Action Set cache on , Then the view will not call again @Html.AntiForgeryToken() Generate a new ,ajax The request still carries the last generated token

ASP.NET MVC4/5 - Ajax prevent CSRF More articles about attacks

  1. How to build ASP.NET MVC4&amp;JQuery&amp;AJax&amp;JSon Example

    background : A small example will be built in the blog , Used to demonstrate in ASP.NET MVC4 In the project , How to use JQuery Ajax. step : 1, Add controller (HomeController) And how to do it (Index), And for Inde ...

  2. ASP.NET MVC prevent CSRF attack

    brief introduction MVC Medium Html.AntiForgeryToken() It is used to prevent cross site request forgery (CSRF:Cross-site request forgery) A measure of the attack , It goes with XSS(XSS Also called CSS:Cr ...

  3. ASP.NET MVC ajax Submit prevent CSRF attack

    // stay View in <script type="text/javascript"> @functions{ public string ToKenHeaderValue( ...

  4. Protect ASP.NET The application is free from CSRF attack

    CSRF What is it? ? CSRF(Cross-site request forgery), Chinese name : Cross-site request forgery , Also known as :one click attack/session riding, Abbreviation for :CSRF/ ...

  5. ajax Medium plus AntiForgeryToken prevent CSRF attack

    Often see in projects ajax post Data to the server without anti-counterfeiting mark , cause CSRF attack stay Asp.net Mvc It's very easy to add anti-counterfeiting marks in the form Html.AntiForgeryToken() that will do . Html.A ...

  6. Remember ajax You have to bring AntiForgeryToken prevent CSRF attack

    Often see in projects ajax post Data to the server without anti-counterfeiting mark , cause CSRF attack stay Asp.net Mvc It's very easy to add anti-counterfeiting marks in the form Html.AntiForgeryToken() that will do . Html.A ...

  7. Bear in mind ajax You have to bring AntiForgeryToken prevent CSRF attack

    It's often seen in Program projects ajax post There is no anti-counterfeiting mark on the data to the server , Lead to CSRF Be attacked , The following small series through this article to introduce ajax You have to bring AntiForgeryToken prevent CSRF attack , Interested friends together ...

  8. Asp.net MVC How to prevent CSRF attack

    What is? CSRF attack ? CSRF(Cross-site request forgery Cross-site request forgery , Also known as "one click attack" perhaps session riding, through ...

  9. Django( sixteen ) Template based login cases : Login decorator 、csrf Attack mode and protection 、ajax Of Post Of csrf Open the writing 、 Generate verification code 、 Login with verification code 、 Reverse DNS + The ginseng

    One .csrf attack 1.1 csrf attack ( Cross-site request forgery ) [csrf Attack is ]: Pass the first 3 Fang's website , Falsify a request ( The premise is that you have logged into the normal website , And saved session or cookie Login information and no exit ), Third party websites ...

Random recommendation

  1. front end SEO skill

    A few days ago in MOOC online learning “SEO Application in web page production ”, I think it's very good . It works , today , Here's a little note , It can also be regarded as a summary after learning . One . How search engines work When we type the key words in the input box , When you click search or query , ...

  2. nodejs Send... To a remote server post request ---- Melting clouds Web SDK/ Client acquisition token

    Recently, we need to use a real-time communication system called rongyun SDK, In obtaining token This step is a bit of a holdup , In case of similar problems in the future , Record again . The client through the cloud SDK Every time you connect to the server , You need to provide Token, In order to test ...

  3. oracle Command line operations

    exp zdxk/zdxk@ORCL TABLES=(ms_data_dictory_def,ms_static_data_def) file=c:\staticdata.dmp By input EXP life ...

  4. function : Embedded functions and closures - Basic learning Python020

    function : Embedded functions and closures Let programming change the world Change the world by program Embedded functions and closures The topics we will talk about in the next two classes may be " More advanced ", So if you're a zero base friend , ...

  5. java_model_dao_ Automatic generation _generator-mybatis-generator-1.3.2 be based on maven plug-in unit

    use mybatis The reason is simple , Easy to use , performance . Is between jdbc and hibernate A perfect solution between . It's simple : 1: To configure pom <project xmlns="http://maven.ap ...

  6. jmeter Response assertion

    jmeter There are many kinds of assertions , In this article, I'll introduce the response assertion that we often use ! Response assertion : Assertion checking of the server's response (1). Range of application Apply to : Main sample and sub-sample ...

  7. Variable type -Tuple

    course : One : Tuple creation          Tuples (tuple) Like a list , The difference is that the elements of a tuple cannot be modified     (1)tuple Between the parentheses , The elements are separated by commas     (2) Tuple elements can be of different types     (3) ...

  8. Centos7 Dual network card binding configuration bonding

    bonding Seven working modes of : bonding Technology offers seven modes of operation , When using it, you need to specify , Each has its own advantages and disadvantages , We use mode=4 balance-rr (mode=0) Default , High availability ( ...

  9. [ Algorithm is summarized ] 13 The problem is solved BAT interview —— character string

    1. KMP Algorithm When it comes to strings , I have to mention that KMP Algorithm , It is used to solve the problem of string lookup , Can be in a string (S) Find a substring in (W) Position of appearance .KMP The algorithm reduces the time complexity of character matching to O(m+ ...

  10. spring cloud Service discovery annotation @EnableDiscoveryClient And @EnableEurekaClient

    Two kinds of annotations are mentioned when using service discovery , One is @EnableDiscoveryClient, One is @EnableEurekaClient, The usage is basically the same , Let's talk about the two today , The following is from stackoverflow ...