Sping Boot Spring Security CSRF 403错误

3okqufwl  于 2023-04-11  发布在  Spring
关注(0)|答案(2)|浏览(228)

当我在项目中使用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>

CartController〈---似乎这个方法没有被调用,因为logger.info(“NUMBER”+cart_id)没有被执行

@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";
    }
}
z2acfund

z2acfund1#

试试这个:-
public class Uncategorized {

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

    
    return "redirect:/cart";
}

}

lmvvr0a8

lmvvr0a82#

我犯了个愚蠢的错误
我没有正确编码Thymeleaf

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

改为

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

相关问题