Why I received an Error 403 with MockMvc and JUnit?

后端 未结 3 1029
夕颜
夕颜 2021-02-02 09:08

I have a spring mvc (3.2.5) application with spring security (3.2).

I configured my SecurityConfig.class with this method :

@Override
protected void co         


        
3条回答
  •  天涯浪人
    2021-02-02 09:46

    Post requests need the CSRF token to be added to the form. So you have to pass it while testing, code: ("it works on my machine" :))

    String TOKEN_ATTR_NAME = "org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN";
    
    // ...
    
    HttpSessionCsrfTokenRepository httpSessionCsrfTokenRepository = new HttpSessionCsrfTokenRepository();
    CsrfToken csrfToken = httpSessionCsrfTokenRepository.generateToken(new MockHttpServletRequest());
    
    this.mockMvc.perform(
                    post("yourpath")
                        .sessionAttr(TOKEN_ATTR_NAME, csrfToken)
                        .param(csrfToken.getParamName(), csrfToken.getToken())...
    

    2nd thing: are you sure that registration" method handles your post request? Isn't RequestMapping configured for "GET" by default? (I may be wrong here)

提交回复
热议问题