如何在spring测试用例中通过认证

时间:2017-10-18 13:31:47

标签: spring spring-boot spring-security

我正在使用带有OAuth 2.0的spring boot 1.5.6。问题是,当我在测试用例下面运行时,我在下面的行上获得了Null指针异常,用于验证对象。

 System.out.println(authentication.getName());

测试类

@RunWith(SpringRunner.class)
@SpringBootTest(classes = WebApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource( locations = "classpath:test-application.properties")
public class ProfileControllerTest {

......
......

     @Before
      public void setup() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
        ...........
        .........
      }

      @Test
      public void profileTest() throws Exception {
        String userId = "12345678";

        mockMvc.perform(get("user/" + userId + "/profile"))
        .andExpect(status().isOk())
          .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
      }
}

休息控制器

  @RequestMapping(value = "user/{userId}/profile",
      method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<Map<String, Object>> getProfile(
      @PathVariable(value = "userId", required = true) String userId,
      HttpServletRequest request, Authentication authentication) {
      System.out.println(authentication.getName());
    }

安全配置

@Configuration
@EnableOAuth2Sso
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {

  private static final String OAUTH_COOKIE = "OAUTH-ACCESS-TOKEN";

  private UserService userService;
  private OAuth2TokenAuthenticationFilter ssoFilter;
  private JwtAccessTokenConverter accessTokenConverter;

  /**
   * WebAppSecurity overloaded constructor.
   */
  public WebAppSecurityConfig(UserService userService,
      OAuth2TokenAuthenticationFilter ssoFilter,
      JwtAccessTokenConverter accessTokenConverter) {
    this.userService = userService;
    this.ssoFilter = ssoFilter;
    this.accessTokenConverter = accessTokenConverter;
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.anonymous()
        .disable()
        .authorizeRequests()
        .antMatchers("/logout-success")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .csrf()
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
        .and()
        .addFilterAfter(ssoFilter,
            AbstractPreAuthenticatedProcessingFilter.class).logout()
        .logoutUrl("/logout").logoutSuccessUrl("/logout-success").permitAll()
        .deleteCookies(OAUTH_COOKIE);
  }

  @Autowired
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService());
    configure((DefaultAccessTokenConverter) accessTokenConverter
        .getAccessTokenConverter());
  }

  protected void configure(DefaultAccessTokenConverter accessTokenConverter) {
    DefaultUserAuthenticationConverter userTokenConverter =
        new DefaultUserAuthenticationConverter();
    userTokenConverter.setUserDetailsService(userDetailsService());
    accessTokenConverter.setUserTokenConverter(userTokenConverter);
  }

  @Override
  protected UserDetailsService userDetailsService() {
    return userService;
  }

如何在上面的测试用例中传递Authentication对象?

1 个答案:

答案 0 :(得分:1)

您可以在测试中使用@WithMockUser注释。

例如:

  @Test
  @WithMockUser(username = "admin", roles = { "ADMIN" }) 
  public void profileTest() throws Exception {
    String userId = "12345678";

    mockMvc.perform(get("user/" + userId + "/profile"))
    .andExpect(status().isOk())
      .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
  }

假设您已为"user/" + userId + "/profile"端点配置并启用了spring-security,则控制器中的System.out.println(authentication.getName());将打印:admin

Spring Securty docs

中的更多详细信息