Spring Security 与 thymeleaf 和 ajax 调用

发布于 2025-01-19 02:49:24 字数 1690 浏览 0 评论 0原文

我使用弹簧启动与弹簧安全性,

@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.authorizeRequests()
            .antMatchers(
                    "/",
                    "/email",
                    "/starter**",
                    "/forgetpassword**",
                    "/resetpassword**",
                    "/register**",
                    "/register/**",
                    "/css/**",
                    "/js/**",
                    "/img/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin().loginPage("/login").permitAll()
            .successHandler(customAuthenticationSuccessHandler)
            .and()
            .logout();

}

我想进行ajax调用以保存信息

@PostMapping("/book")
public ResponseEntity generateBook(@RequestBody Book book){

}

,我尝试了此信息,但是我得到了一个403,

$.ajax({
    url : 'http://localhost:8080/book',
    type : 'post',
    contentType: 'application/json',
    dataType: "json",
    headers:{
        '_csrf' : '[[${_csrf.token}]]',
        '_csrf_header' : '[[${_csrf.headerName}]]'
    },
    data : '....',
    success : function(response) {
        debugger;
        ...
    }
});

我启用了spring Security Log,用该

logging.level.org.springframework.security=DEBUG

编辑

我得到了这个

为http:// localhost找到的无效CSRF令牌:8080/book
响应403状态代码

我只是不明白为什么?

令牌的值是由服务器

编辑2

方案生成的,这是

用户日志到系统,当他单击“生成书本启动”时,他将带有按钮到达页面。

生成图书失败,如果用户尝试更改其密码,我会看到与由csrf代币相同的值

[[${_csrf.token}]]

I use spring boot with spring-security

@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.authorizeRequests()
            .antMatchers(
                    "/",
                    "/email",
                    "/starter**",
                    "/forgetpassword**",
                    "/resetpassword**",
                    "/register**",
                    "/register/**",
                    "/css/**",
                    "/js/**",
                    "/img/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin().loginPage("/login").permitAll()
            .successHandler(customAuthenticationSuccessHandler)
            .and()
            .logout();

}

I want to do ajax call to save information

@PostMapping("/book")
public ResponseEntity generateBook(@RequestBody Book book){

}

I tried this but i get a 403

$.ajax({
    url : 'http://localhost:8080/book',
    type : 'post',
    contentType: 'application/json',
    dataType: "json",
    headers:{
        '_csrf' : '[[${_csrf.token}]]',
        '_csrf_header' : '[[${_csrf.headerName}]]'
    },
    data : '....',
    success : function(response) {
        debugger;
        ...
    }
});

I enabled spring security log with that

logging.level.org.springframework.security=DEBUG

Edit

I get this

Invalid CSRF token found for http://localhost:8080/book
Responding with 403 status code

I just don't understand why?

the value of the token is generated by the server

Edit 2

Scenario is

User log to the system, he arrive on page with a button, When He click generate book start.

Generate book fail, if user try to change its password, i see the same csrf token value than the one created by

[[${_csrf.token}]]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怎樣才叫好 2025-01-26 02:49:24

将这些行添加到头标签中:

<meta id="_csrf" name="_csrf" th:content="${_csrf.token}"/>
<meta id="_csrf_header" name="_csrf_header" th:content="${_csrf.headerName}"/>

和Ajax请求:

var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
//Add beforeSend to the ajax call, like:
$.ajax({
       type: ‘POST’,
       url: url,
       beforeSend: function(request) {
           request.setRequestHeader(header, token);
       },
       data: data
}); 

Add these lines to head tag:

<meta id="_csrf" name="_csrf" th:content="${_csrf.token}"/>
<meta id="_csrf_header" name="_csrf_header" th:content="${_csrf.headerName}"/>

And in the AJAX request:

var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
//Add beforeSend to the ajax call, like:
$.ajax({
       type: ‘POST’,
       url: url,
       beforeSend: function(request) {
           request.setRequestHeader(header, token);
       },
       data: data
}); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文