javascript
Spring MVC,Thymeleaf,Spring Security应用程序中的CSRF保护
跨站點請求偽造(CSRF)是一種攻擊,它迫使最終用戶在當前已通過身份驗證的Web應用程序上執(zhí)行不需要的操作。 如果您使用Spring Security 3.2及更高版本,在Spring MVC / Thymeleaf應用程序中防止CSRF攻擊相當容易。
怎么測試?
為了進行測試,我創(chuàng)建了一個區(qū)域受限的應用程序,可以在其中發(fā)送表單。 表單的源代碼:
知道操作URL是http:// localhost:8080 / message之后,我創(chuàng)建了一個單獨的頁面,其中包含一個引用該URL(帶有所有參數(shù))的HTTP請求:
<!DOCTYPE html> <html> <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <form action="http://localhost:8080/message" method="post"><input type="hidden" name="payload" value="Hacked content!"/><input type="submit" value="Hack!" /> </form> </body> </html>我登錄了該應用程序并執(zhí)行了上面的代碼。 當然,服務器允許我執(zhí)行請求,因為我的應用程序容易受到CSRF攻擊。 要了解有關CSRF測試的更多信息,請訪問此鏈接: CSRF測試 。
如何保護?
如果您將XML配置與Spring Security一起使用,則必須啟用CSRF保護:
<security:http auto-config="true" disable-url-rewriting="true" use-expressions="true"><security:csrf /><security:form-login login-page="/signin" authentication-failure-url="/signin?error=1"/><security:logout logout-url="/logout" /><security:remember-me services-ref="rememberMeServices" key="remember-me-key"/><!-- Remaining configuration --></security:http>如果是Java配置–默認情況下啟用。
從Thymeleaf 2.1版本開始,CSRF令牌將自動添加到具有隱藏輸入的表單中:
<form class="form-narrow form-horizontal" method="post" action="/message"><!-- Fields --><input type="hidden" name="_csrf" value="16e9ae08-76b9-4530-b816-06819983d048" /></form>現(xiàn)在,當您嘗試重復攻擊時,將看到“ 訪問被拒絕”錯誤。
但是要記住的一件事是,啟用CSRF保護可確保注銷需要CSRF令牌。 我使用JavaScript提交了隱藏表格:
<a href="/logout" th:href="@{#}" onclick="$('#form').submit();">Logout</a><form style="visibility: hidden" id="form" method="post" action="#" th:action="@{/logout}"></form>摘要
在這篇簡短的文章中,我展示了在使用Spring MVC(3.1 +),Thymeleaf(2.1+)和Spring Security(3.2+)時,如何輕松利用CSRF保護。 從Spring Security 4開始,使用XML配置時,默認情況下也會啟用CSRF。 請注意,使用HTTP會話來存儲CSRF令牌。 但這很容易改變。 有關更多詳細信息,請參見參考。
- 我在Spring MVC原型中包含CSRF配置。 請檢查!
資源資源
- Thymeleaf –與RequestDataValueProcessor集成
- Spring安全– CSRF攻擊
- OWASP –跨站請求偽造(CSRF)
翻譯自: https://www.javacodegeeks.com/2014/04/csrf-protection-in-spring-mvc-thymeleaf-spring-security-application.html
總結
以上是生活随笔為你收集整理的Spring MVC,Thymeleaf,Spring Security应用程序中的CSRF保护的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 黑石深渊在哪 位置介绍
- 下一篇: 大秦赋台词彩是什么意思 大秦赋台词彩含义