Spring Boot Spring Security CSRF 403 错误

问题描述 投票:0回答:2

当我在项目中使用Spring Security时

我的购物车出现 403 错误

CartController 的 logger.info("NUMBER"+cart_id) 没有执行

可能是 CSRF 问题

Cart.html

<form method="post" action="orderAdd">
            <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
                <table class="alt">
                    <thead>
                    <tr>
                        ...
                    </tr>
                    </thead>
                    
                    <tbody>
                    
                    <tr th:each="Cart:${cartVO}">
                        
                        <td style="vertical-align: middle;" width="120">
                        <input type="checkbox" th:value="${Cart.cart_id}" name="valCartId" id="cid" style="opacity:1;appearance:checkbox;margin-right:0"/>
                        
                        <strong th:text="${Cart.name}" ></strong>
                        
                        </td>

                        <td style="width: 123px; height: 124px;"><a
                                href="" class="image"><img th:src="@{${Cart.image}}"
                            alt="productIMG" height="100" /></a></td>
                        <td th:text="${Cart.spec}" style="vertical-align: middle;" width="70"></td>
                        <td th:text="${Cart.price}" style="vertical-align: middle;" width="50"></td>
                        <td th:text="${Cart.cart_Quantity}" style="vertical-align: middle;" width="70"></td>
                    </tr>
                    
                    </tbody>
                   
                </table>
                <div class="col-12">
                        <ul class="actions">
                            <li><input type="submit" value="BUY" class="primary" /></li>
                            <li><input type="submit" value="DELETE" formaction="/cartDelete"/></li>
                        </ul>
                    </div>
              </form>

购物车控制器<--- It seems that this method is not call, because logger.info("NUMBER"+cart_id) is not executed

@Controller
public class CartController {

@PostMapping("/cartDelete")
    public String delete(@RequestParam("valCartId") List<Long> cart_id) {
            logger.info("NUMBER"+cart_id);
            cartService.delete(cart_id);

        
        return "redirect:/cart";
    }
}
spring-boot spring-security thymeleaf csrf
2个回答
0
投票

试试这个:-

@控制器 公共类 CartController {

@DeleteMapping("/cartDelete/{cart_id}")
public String delete(@PathVariable Long cart_id) {
        logger.info("NUMBER"+cart_id);
        cartService.delete(cart_id);

    
    return "redirect:/cart";
}

}


0
投票

我犯了一个愚蠢的错误

我没有正确编码 Thymeleaf

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

改为

<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
© www.soinside.com 2019 - 2024. All rights reserved.