Spring Test & Security: How to mock authentication?

后端 未结 7 1544
野性不改
野性不改 2020-11-28 01:27

I was trying to figure out how to unit test if my the URLs of my controllers are properly secured. Just in case someone changes things around and accidentally removes securi

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 01:43

    Short answer:

    @Autowired
    private WebApplicationContext webApplicationContext;
    
    @Autowired
    private Filter springSecurityFilterChain;
    
    @Before
    public void setUp() throws Exception {
        final MockHttpServletRequestBuilder defaultRequestBuilder = get("/dummy-path");
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext)
                .defaultRequest(defaultRequestBuilder)
                .alwaysDo(result -> setSessionBackOnRequestBuilder(defaultRequestBuilder, result.getRequest()))
                .apply(springSecurity(springSecurityFilterChain))
                .build();
    }
    
    private MockHttpServletRequest setSessionBackOnRequestBuilder(final MockHttpServletRequestBuilder requestBuilder,
                                                                 final MockHttpServletRequest request) {
        requestBuilder.session((MockHttpSession) request.getSession());
        return request;
    }
    

    After perform formLogin from spring security test each of your requests will be automatically called as logged in user.

    Long answer:

    Check this solution (the answer is for spring 4): How to login a user with spring 3.2 new mvc testing

提交回复
热议问题