gpt4 book ai didi

java - 使用spring security时如何在velocity宏中获取csrf token

转载 作者:行者123 更新时间:2023-12-02 20:58:10 30 4
gpt4 key购买 nike

我正在尝试为启用 Spring Web Security 的应用程序创建自定义登录屏幕,但我无法弄清楚如何将 csrf token 传递给velocity(不,我目前无法使用 JSP)。

模型看起来像这样:

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username or password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}

速度模板的相关部分如下所示(从 jsp 示例中获取并修改):

    <form name='loginForm' action="/login" method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>

当然,${_csrf.parameterName}${_csrf.token} 变量为空,因此只有在禁用 csrf 保护时才有效。所以我的主要问题是:如何将它们填充到模型中(或其他任何地方)?

最佳答案

我已经找到了解决方案,要点是csrf token通过CsrfFilter注入(inject)到HttpServletRequest中,只需在处理请求映射的方法中添加一个HttpServletRequest参数就可以获取HttpServletRequest对象。

所以需要做的改变是:

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout,
HttpServletRequest request
){
...
CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
if (csrfToken != null) {
model.addObject("_csrf",csrfToken);
}
...

关于java - 使用spring security时如何在velocity宏中获取csrf token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25625056/

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