gpt4 book ai didi

java - 如何使用 Spring security 测试基于数据库的用户的 JWT 身份验证?

转载 作者:太空宇宙 更新时间:2023-11-04 09:29:38 29 4
gpt4 key购买 nike

我有一个带有 JWT 身份验证的小型 Spring Boot 2.1.6 Web 应用程序。调用流程如下:

  1. 用户输入用户名和密码并向/authenticate 发送 POST 请求
  2. 过滤器正在监视此 URL (setFilterProcessesUrl),当请求到来时,它会对密码进行哈希处理,并根据数据库中存储的哈希值进行检查
  3. 如果匹配,并且用户未锁定,它将创建一个包含用户名和授予角色的 JWT,并在响应中返回它
  4. 用户必须在所有进一步的请求中包含此 JWT

此外,CSRF 在 WebSecurityConfigurerAdapter 中被禁用。

解决方案本身工作正常,但我还必须创建单元测试。我最终得到了以下测试用例:

@RunWith(SpringRunner.class)
@WebMvcTest
@ContextConfiguration(classes = { ConfigReaderMock.class })
public class ControllerSecurityTest {

private static final String VALID_USERNAME = "username";
private static final String VALID_PASSWORD = "password";

@Autowired
private MockMvc mockMvc;

private String createAuthenticationBody(String username, String passwordHash) {
return "username=" + URLEncoder.encode(username, StandardCharsets.UTF_8) + "&password="
+ URLEncoder.encode(passwordHash, StandardCharsets.UTF_8);
}

@Test
public void testValidLogin() throws Exception {
MvcResult result = mockMvc
.perform(MockMvcRequestBuilders.post("/authenticate")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.content(createAuthenticationBody(VALID_USERNAME, VALID_PASSWORD)).accept(MediaType.ALL))
.andExpect(status().isOk()).andReturn();

String authHeader = result.getResponse().getHeader(SecurityConstants.TOKEN_HEADER);

mockMvc.perform(MockMvcRequestBuilders.get("/main?" + SecurityConstants.TOKEN_QUERY_PARAM + "="
+ URLEncoder.encode(authHeader, StandardCharsets.UTF_8))).andExpect(status().isOk());
}
}

我期望的是,服务器接受提供的用户名和密码,并返回 JWT,我可以在后续请求中使用它来访问下一个页面(前端也实现了相同的功能)。相反,我从身份验证过滤器获取 HTTP 403:

MockHttpServletRequest:
HTTP Method = POST
Request URI = /authenticate
Parameters = {username=[username], password=[password]}
Headers = [Content-Type:"application/x-www-form-urlencoded", Accept:"*/*"]
Body = <no character encoding set>
Session Attrs = {org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@4ac0fdc7}

Handler:
Type = null

Async:
Async started = false
Async result = null

Resolved Exception:
Type = null

ModelAndView:
View name = null
View = null
Model = null

FlashMap:
Attributes = null

MockHttpServletResponse:
Status = 403
Error message = Forbidden
Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []

我注意到它出于某种原因在 session 属性中发送 CSRF token 。进一步检查日志,我可以看到以下消息:

2019-07-29 08:09:17,438 DEBUG o.s.b.f.s.DefaultSingletonBeanRegistry [main] Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.security.servlet.WebSecurityEnablerConfiguration'
2019-07-29 08:09:17,443 DEBUG o.s.s.c.a.a.c.AuthenticationConfiguration$EnableGlobalAuthenticationAutowiredConfigurer [main] Eagerly initializing {org.springframework.boot.autoconfigure.security.servlet.WebSecurityEnablerConfiguration=org.springframework.boot.autoconfigure.security.servlet.WebSecurityEnablerConfiguration$$EnhancerBySpringCGLIB$$236da03c@4e68aede}
2019-07-29 08:09:17,444 DEBUG o.s.b.f.s.DefaultSingletonBeanRegistry [main] Creating shared instance of singleton bean 'inMemoryUserDetailsManager'
2019-07-29 08:09:17,445 DEBUG o.s.b.f.s.DefaultSingletonBeanRegistry [main] Creating shared instance of singleton bean 'org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration'
2019-07-29 08:09:17,454 DEBUG o.s.b.f.s.DefaultSingletonBeanRegistry [main] Creating shared instance of singleton bean 'spring.security-org.springframework.boot.autoconfigure.security.SecurityProperties'
2019-07-29 08:09:17,457 DEBUG o.s.b.f.s.ConstructorResolver [main] Autowiring by type from bean name 'inMemoryUserDetailsManager' via factory method to bean named 'spring.security-org.springframework.boot.autoconfigure.security.SecurityProperties'
2019-07-29 08:09:17,462 INFO o.s.b.a.s.s.UserDetailsServiceAutoConfiguration [main]

Using generated security password: 963b2bac-d953-4793-a8cd-b3f81586823e

...

2019-07-29 08:09:17,783 DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository [main] No HttpSession currently exists
2019-07-29 08:09:17,784 DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository [main] No SecurityContext was available from the HttpSession: null. A new one will be created.
2019-07-29 08:09:17,794 DEBUG o.s.s.w.c.CsrfFilter [main] Invalid CSRF token found for http://localhost/authenticate
2019-07-29 08:09:17,795 DEBUG o.s.s.w.h.w.HstsHeaderWriter [main] Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@1c15a6aa
2019-07-29 08:09:17,796 DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository$SaveToSessionResponseWrapper [main] SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2019-07-29 08:09:17,799 DEBUG o.s.s.w.c.SecurityContextPersistenceFilter [main] SecurityContextHolder now cleared, as request processing completed

因此,Spring Security 似乎正在创建自己的安全配置,而不是使用我创建的类来扩展 WebSecurityConfigurerAdapter。问题是,为什么?我如何强制它使用我的安全配置,因为我的数据库登录依赖于它?

更新:添加了 WebSecurityConfigurerAdapter

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private AICAuthenticationService authenticationService;

@Autowired
private AICUserDetailsService aicUserDetailsService;

@Autowired
private AICLogoutSuccessHandler aicLogoutSuccessHandler;

@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.cors()
.and()
.authorizeRequests()
.antMatchers("/resources/**", "/login", "/").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
.addFilter(new JwtAuthorizationFilter(authenticationManager()))
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(aicLogoutSuccessHandler)
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID", "error");
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(aicUserDetailsService);
}

@Override
protected AuthenticationManager authenticationManager() throws Exception {
return authenticationService;
}

@Bean
public AuthenticationManager custromAuthenticationManager() throws Exception {
return authenticationManager();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(aicUserDetailsService);
}

最佳答案

我能够使用 TestRestTemplate 完成它,如下所示:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ControllerSecurityTest {

private static final String VALID_USERNAME = "username";
private static final String VALID_PASSWORD = "password";

@LocalServerPort
private int port;

@Autowired
private TestRestTemplate restTemplate;

@Test
public void testValidLogin() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setAccept(Arrays.asList(MediaType.ALL));

MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("username", VALID_USERNAME);
map.add("password", VALID_PASSWORD);

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

ResponseEntity<String> tokenResponse = restTemplate
.postForEntity("http://localhost:" + port + "/authenticate", request, String.class);

assertEquals(200, tokenResponse.getStatusCodeValue());

String authHeader = tokenResponse.getHeaders().getFirst(SecurityConstants.TOKEN_HEADER);

assertNotNull(authHeader);

ResponseEntity<String> mainResponse = restTemplate.getForEntity("http://localhost:" + port + "/main?"
+ SecurityConstants.TOKEN_QUERY_PARAM + "=" + URLEncoder.encode(authHeader, StandardCharsets.UTF_8),
String.class);

assertEquals(200, mainResponse.getStatusCodeValue());
}
}

关于java - 如何使用 Spring security 测试基于数据库的用户的 JWT 身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57248292/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com