Mocking a Keycloak token for testing a Spring controller

后端 未结 2 1299
星月不相逢
星月不相逢 2021-02-13 17:46

I want to write unit tests for my spring controller. I\'m using keycloak\'s openid flow to secure my endpoints.

In my tests I\'m using the @WithMockUser ann

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-13 18:09

    I was able to test after adding the following things:

    1. Add some fields:

      @Autowired
      private WebApplicationContext context;
      
      private MockMvc mockMvc;
      
    2. In my @Before setup() method:

      mockMvc = MockMvcBuilders.webAppContextSetup(context)
         .alwaysDo(print())
         .apply(springSecurity())
         .build(); 
      
    3. Inside my test method:

      SecurityContext context = SecurityContextHolder.getContext();
      Authentication authentication = context.getAuthentication();
      

    When I pass the authentication object to the method where I read the claims from the keycloak token I can run the test without any problems.

    P.S. Don't forget the @WithMockUser annotation

提交回复
热议问题