我可以使用Spring Security的CSRF功能而不使用其LOGIN和LOGOUT功能吗?
我使用的是HTML页面而不是JSP,我想要Spring csrf令牌来处理我发出的所有POST请求。 对于登录,我们使用的是AWS Cognito。
答案 0 :(得分:2)
是的,您可以将其与HTML一起使用,因为Spring Security
已默认启用。我已经将它与Thymeleaf
一起用于服务器端。
基本上,您可以像这样在HTML文件中简单地命名thymeleaf命名空间。
<html lang="en" xmlns:th="http://www.thymeleaf.org">
...
spring应用程序,您应该在下面导入依赖项,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在application.yml
(或application.properties
)文件中进行以下配置。
spring:
thymeleaf:
enabled: true
prefix: classpath:/static/ # This static directory located in the resource folder of maven directory structure and all the html and its css/js resources go in there.
suffix: .html
cache: false
enable-spring-el-compiler: true
check-template: true
mode: HTML
encoding: UTF-8
否,您可以仅使用html标头部分中的两个元标记将CSRF
令牌添加到网页。
<meta name="_csrf" th:content="${_csrf.token}">
<meta name="_csrf_headerName" th:content="${_csrf.headerName}">
或者,如果您使用的是<form>
提交,请将此隐藏的输入字段添加到<form>
中,
<input th:name="${_csrf.parameterName}" th:value="${_csrf.token}" type="hidden"/>
如果您已经在meta标记中定义了它们,并且需要发出Ajax请求,则这是JQuery代码段;
$.ajax({
url: '/url',
method: 'POST',
data: {"some": "data"},
beforeSend: (jqXHR) => {
jqXHR.setRequestHeader(
$("meta[name='_csrf_headerName']").attr('content'),
$("meta[name='_csrf']").attr('content'));
},
success: (data, textStatus, jqXHR) => {
// if success.
},
error: (jqXHR) => {
// if error.
},
complete: (jqXHR, textStatus) => {
// Anyway completed.
}
});
答案 1 :(得分:0)
是的,您可以做到。但这与csrf概念冲突。
在spring security configurer类中编写此代码
private final String LOGIN_URL= "";//your login url
private final String LOGOUT_URL = "";//your logout url
protected void configure(HttpSecurity http) throws Exception {
// other code here.........
http.csrf().ignoringAntMatchers(LOGIN_URL, LOGOUT_URL);
}