Cross-site request forgery Cross-site Request Forgery, also known as one-click attack or session riding, usually abbreviated as CSRF or XSRF, Is a method of hijacking a user to perform unintended actions on a currently logged Web application. In contrast to cross-site scripting (XSS), which exploits the user’s trust in a given site, CSRF exploits the site’s trust in the user’s Web browser. A cross-site request attack, simply put, is a technique by which an attacker tricks a user’s browser into visiting a previously authenticated web site and performing operations (such as emailing, sending messages, or even property operations such as transferring money or buying goods). Because the browser has been authenticated, the site being visited will act as if it were a genuine user action. This exploits a flaw in user authentication on the Web: simple authentication can only guarantee that a request is sent from a user’s browser, but not that the request itself is voluntarily made by the user.

Starting with Spring Security 4.0, CSRF protection is enabled by default to prevent CSRF from attacking applications. Spring Security CSRF protects against PATCH, POST, PUT, and DELETE methods.

Add the following paragraph to your login page to use it

<input 
type="hidden"th:if="${_csrf}! =null"th:value="${_csrf.token}"name="_csrf
"/>
Copy the code
<! doctype html> <html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="Width =device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<form action="/user/login" method="post"> <! -- Prevent XSS attacks --> <input type="hidden"th:if="${_csrf}! =null"th:value="${_csrf.token}"name="_csrf
"/> User name :<input type="text" name="username"/><br/> Password: <input type="password" name="password"/><br/>
    <input type="checkbox"name="remember-me"title="Remember the password"Remember the password <br/> <input type="submit" value="Submit"/>
</form>
</body>
</html>
Copy the code

Disable CSRF in classes for security configuration

// http.csrf().disable();
Copy the code

Principle:

  1. CsrfToken is generated and stored in HttpSession or Cookie

.

  1. When the request arrives, the csrfToken is extracted from the request and compared with the saved csrfToken to determine when

Whether the previous request is valid. Mainly through the CsrfFilter filter to complete.