Spring Test & Security: How to mock authentication?

后端 未结 7 1491
野性不改
野性不改 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 02:08

    Since Spring 4.0+, the best solution is to annotate the test method with @WithMockUser

    @Test
    @WithMockUser(username = "user1", password = "pwd", roles = "USER")
    public void mytest1() throws Exception {
        mockMvc.perform(get("/someApi"))
            .andExpect(status().isOk());
    }
    

    Remember to add the following dependency to your project

    'org.springframework.security:spring-security-test:4.2.3.RELEASE'
    
    0 讨论(0)
提交回复
热议问题