spring security測試相關

##測試spring

  • 基本引用,讀取測試上下文

@Runwith(springJUnit4ClassRunner.class) @ContextConfigurationide

  • 去掉異常

@Test(expected=AuthenticationCredentialsNotFoundException.class)學習

  • 使用模擬用戶

@Test @WithMockUser測試

  • 給模擬用戶添加用戶名 @Test @WithMockUser("customUsername").net

  • 給模擬用戶添加角色 @Test @WithMockUser(username="admin",roles={"USER","ADMIN"})code

  • 給模擬用戶添加受權 @Test @WithMockUser(username="admin",authorities={"ADMIN","USER"})對象

  • 添加一個匿名對象.ip

@WithAnonymousUser 在方法上使用,使之得到一個匿名對象.ci

###使用@WithUserDetailsget

@WithMockUser適合初始學習,可是不會適合全部應用.它不適合那種指定了Authentication特定類型的主體.這樣就能夠指定任意的主體,並減小與spring security的耦合.

自定義當事人常常返回一個自定義的UserDetailsService,並返回實現了UserDetails和自定義類型的對象.這種狀況下,它對於檢測自定義的userDetailsService就很是有用.這個就是@WithUserDetails的工做.

假設UserDetailsService做爲一個bean暴露.在下面的測試中UserDetailsService將暴露一個名爲"user"的 UsernamepasswordAuthenticationToken類型的Authentication及其主體.

@Test @WithUserDetails public void getMessageWithUserDetails() { String message = messageService.getMessage(); ... }

咱們也能夠經過設置username來查找相應的principal.

@Test @WithUserDetails("customUsername")

另外,咱們能夠指定bean的名稱 @Test @WithUserDetails(value="customUsername",userDetailsServiceBeanName="myUserDetailsService")

注: 這個註解要求其對應的用戶必須存在

###@WithSecurityContext 咱們能夠經過@WithSecurityContext來建立咱們須要的Security.例如,以下建立一個@WithMockCustomer

@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory=WithMockCustomUserSecurityContextFactory.class)

public @interface WithMockCustomUser{
	String username() default "rob";
	String name() default "Rob Winch";
}

@WithMockCustomUser須要一個WithSecurityContextFacotry的實現類,是實現類代碼以下:

public class withMockCustomerSecurityContextFactory implements WithSecurityContextFacotry<WithMockCustomUser>{
@Override
public SecurityContext createSecurityContext(WithMockCustomUser customUser){
	SecurityContext context = SecurityContextHolder.createEmptyContext();

		CustomUserDetails principal =
			new CustomUserDetails(customUser.name(), customUser.username());
		Authentication auth =
			new UsernamePasswordAuthenticationToken(principal, "password", principal.getAuthorities());
		context.setAuthentication(auth);
		return context;
}

}

spring security的WithSecurityContextTestExecutionListener能夠保證咱們的操做正確運行.

在建立WithSecurityContextFactory 實現時,咱們能夠使用spring的標準註解.

###經過元註解來生成新的註解

咱們能夠利用@WithMockUser來生成新註解.

@Retention(RetentionPolicy.RUNTIME)
@WithMockUser(value="rob",roles="ADMIN")
public @interface WithMockAdmin{}
相關文章
相關標籤/搜索