【问题标题】:Cannot get the token from request in the controller无法从控制器中的请求中获取令牌
【发布时间】:2015-04-15 18:21:35
【问题描述】:

我正在尝试在 Spring 中测试 loginController,但无法从请求中获取令牌。 在我的测试中

   private CsrfToken token; 
   HttpServletRequest request = new MockHttpServletRequest();

     @Before
     public void setUp() throws Exception {        
         MockitoAnnotations.initMocks(this);
         this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();        
         token = new DefaultCsrfToken("1", "a", "b"); 
         request.setAttribute(CsrfToken.class.getName(), token); 
     }

    @Test
    public void testCtrlCorrecltyHandlesPassword() throws Exception {         
        CsrfToken token2 = (CsrfToken) request.getAttribute(CsrfToken.class.getName());

        MvcResult result = this.mockMvc.perform(get("/rest/login")
                .param("name", name)
                .param("password", password)
                .param("request", request.toString())
                //.sessionAttr("request", request)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andReturn();
    }

当我调试时,我看到 token2 已成功创建,我从请求中获取它的值,但是当我尝试使用完全相同的方式时,在控制器中

CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());

为空。

我还尝试将.sessionAttr("request", request)@ModelAttribute("request")HttpServletRequest request 作为控制器中的参数,但它不起作用。

【问题讨论】:

  • 我更新了我的问题,以防有人可以帮助我,谢谢

标签: java spring token


【解决方案1】:

最终……

    MockHttpSession session = new MockHttpSession();
    session.setAttribute("token", token);

    MvcResult result = this.mockMvc.perform(get("/rest/login").session(session)
            .header("X-Csrf-Token", "")
            .requestAttr(CsrfToken.class.getName(), token)
            .param("name", name)
            .param("password", password)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();

【讨论】:

    猜你喜欢
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 2014-02-17
    • 2019-11-08
    相关资源
    最近更新 更多