谁能告诉我如何模拟SpringSecurity和OncePerRequestFilter(JWT身份验证过滤器)?
互联网上有一些例子,但是我无法一起收集这些例子。
所以,有SpringBoot 2.0。 有一个用户来自@AuthenticationPrincipal作为函数参数。
有一个JWtFilter扩展OncePerRequestFilter,它检查jwt令牌的有效性。
必要
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = NfaBackendApplication.class)
@TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
WithSecurityContextTestExecutionListener.class })
public class OfferControllerTest extends AbstractTestNGSpringContextTests
{
private MockMvc mockMvc;
@Autowired
private WebApplicationContext context;
@MockBean
private UserRepository kvUserRepository;
@InjectMocks
private JWTAuthenticationFilter jwtAuthenticationFilter = new JWTAuthenticationFilter();
@Mock
private JWTokenProvider jwtTokenProvider;
@BeforeClass
public void setUp() throws ServletException, IOException
{
mockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity())
.build();
MockitoAnnotations.initMocks(this);
}
@Test(enabled = true)
public void getExternalOffers() throws Exception
{
// KVUserDetails user = new KVUserDetails("mail@mail.ua", "test", false, true, AuthorityUtils
// .createAuthorityList("ADMIN"));
// TestingAuthenticationToken testingAuthenticationToken = new TestingAuthenticationToken(user, null);
// SecurityContextHolder.getContext().setAuthentication(testingAuthenticationToken);
MockFilterChain filterChain = new MockFilterChain();
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(HttpHeaders.AUTHORIZATION,"Authorized");
MockHttpServletResponse response = new MockHttpServletResponse();
when(jwtTokenProvider.validateToken("Authorized")).thenReturn(true);
mockMvc.perform(get("/admin/offers")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
请告诉我如何润湿SpringSecurity和OncePerRequestFilter(JWT身份验证过滤器)的工作示例?
根据要求,用户将获得AuthenticationPrincipal。
感谢。
答案 0 :(得分:0)
您可以使用@WithUserDetails
初始化用户进行MockMvc测试。无需模拟servlet过滤器。
这样的事情:
@Test(enabled = true)
@WithUserDetails("mail@mail.ua")
public void getExternalOffers() throws Exception
{