gpt4 book ai didi

java - 如何将csrf token添加到html表单中?

转载 作者:行者123 更新时间:2023-12-02 06:21:14 31 4
gpt4 key购买 nike

在我的应用程序中启用 csrf(删除行 .csrf().disable())后,我的登录请求停止工作 - /login POST 将我重定向到主页:

请求如下所示:
enter image description here

在页面上我有以下js:

<script type="text/javascript" src="/webjars/js-cookie/js.cookie.js"></script>
...
$('#login-form').submit(function (ev) {
ev.preventDefault(); // to stop the form from submitting
var headerName = "X-CSRF-TOKEN";
var token = Cookies.get('XSRF-TOKEN')
$('<input>').attr('type', 'hidden').attr('name', '_csrf').attr('value', Cookies.get('XSRF-TOKEN')).appendTo('#login-form');
this.submit(); // If all the validations succeeded
})

你能澄清一下我做错了什么吗?

附注

我读了很多相关的东西,到处都发现了这样的行:

<meta name="_csrf" content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>

我不明白应该如何设置值_csrf.headerName

我尝试将这些数据添加到元位,但它无法解析:
enter image description here

我尝试将其直接添加到表单中:

enter image description here

又没有成功。

另外我尝试了这个:

enter image description here

但正如你所看到的 - 它也不能解析我的属性

附注2

配置:

EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

private static final String SECURE_ADMIN_PASSWORD = "rockandroll";

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/index.html")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/sender.html")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/index.html")
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/js/**", "/lib/**", "/images/**", "/css/**", "/index.html", "/","/*.css","/webjars/**", "/*.js").permitAll()
.antMatchers("/websocket").hasRole("ADMIN")
.requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
.anyRequest().authenticated();

}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

auth.authenticationProvider(new AuthenticationProvider() {

@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;

List<GrantedAuthority> authorities = SECURE_ADMIN_PASSWORD.equals(token.getCredentials()) ?
AuthorityUtils.createAuthorityList("ROLE_ADMIN") : null;

return new UsernamePasswordAuthenticationToken(token.getName(), token.getCredentials(), authorities);
}
});
}
}

构建.gradle:

buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.1.RELEASE")
}
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

jar {
baseName = 'gs-messaging-stomp-websocket'
version = '0.1.0'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
mavenCentral()
}

dependencies {
compile("org.springframework.boot:spring-boot-starter-websocket")
compile("org.webjars:webjars-locator-core")
compile("org.webjars:sockjs-client:1.0.2")
compile("org.webjars:stomp-websocket:2.3.3")
compile("org.webjars:bootstrap:3.3.7")
compile("org.webjars:jquery:3.1.0")
compile("org.webjars:js-cookie:2.1.0")

compile("org.springframework.boot:spring-boot-starter-actuator")
//security
compile ('org.springframework.security:spring-security-messaging')
compile group: 'org.springframework.security', name: 'spring-security-web'
compile group: 'org.springframework.security', name: 'spring-security-config'

testCompile("org.springframework.boot:spring-boot-starter-test")
}

最佳答案

我尝试了不同的方法,最终找到了解决方案:

以前 index.html 位于文件夹 /resources/static

我把它放在文件夹/resources/templates中。我还添加了依赖项:

compile('org.thymeleaf:thymeleaf-spring5');

并显式声明 Controller :

@RequestMapping("/")
public String index(){
return "index";
}

index.html 看起来像这样:

<html lang="en" ng-app="springChat" xmlns:th="http://www.springframework.org/schema/beans">
<head>
...
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_parameter_name" th:content="${_csrf.parameterName}"/>

....
</body>
<script type="application/javascript">

$('#login-form').submit(function (ev) {
ev.preventDefault(); // to stop the form from submitting
var token = $("meta[name='_csrf']").attr("content");
var paramName = $("meta[name='_csrf_parameter_name']").attr("content");
$('<input>').attr('type', 'hidden').attr('name', paramName).attr('value', token).appendTo('#login-form');

this.submit();
});
</script>
</html>

如果我们没有显式声明映射并且不尝试插入诸如 th:content="${ 之类的值,则看起来 Spring Boot 在 /resources/static 原始 html 中搜索_csrf.token}” 到变量中。

关于java - 如何将csrf token添加到html表单中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50065905/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com