使用spring security时如何在速度宏中获取csrf令牌 [英] How to obtain csrf token in a velocity macro when using spring security

查看:150
本文介绍了使用spring security时如何在速度宏中获取csrf令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a custom login screen for a spring web security enabled application, and I cannot figure out how to pass the csrf token to velocity (no, I cannot use JSP at the moment).

该模型如下所示:

@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示例中获取和修改):

And the relevant section of the velocity template looks like (taken and modified from a jsp example):

    <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保护时才有效。所以我的主要问题是:如何在模型中(或其他任何地方)填写它们?

Of course, the ${_csrf.parameterName} and ${_csrf.token} variables are empty, so this only works if I disable csrf protection. So my main question is: how do I fill them in the model (or anywhere else)?

推荐答案

我找到了解决方案,重点是CsrfFilter将csrf令牌注入到HttpServletRequest中,只需在处理请求映射的方法中添加HttpServletRequest参数即可获取HttpServletRequest对象。

I have found the solution, the main point is that the csrf token is injected into the HttpServletRequest by the CsrfFilter, and you can get the HttpServletRequest object by just adding a HttpServletRequest parameter to your method that handles the request mapping.

所以需要做的更改是:

@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);
    }
...

这篇关于使用spring security时如何在速度宏中获取csrf令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆