Spring Security(三十五):Part III. Testing

This section describes the testing support provided by Spring Security.html

本節介紹Spring Security提供的測試支持。

To use the Spring Security test support, you must include spring-security-test-4.2.10.RELEASE.jar as a dependency of your project.java

要使用Spring Security測試支持,必須將spring-security-test-4.2.10.RELEASE.jar做爲項目的依賴項。

11. Testing Method Security

This section demonstrates how to use Spring Security’s Test support to test method based security. We first introduce a MessageService that requires the user to be authenticated in order to access it.spring

本節演示如何使用Spring Security的Test支持來測試基於安全性的方法。咱們首先介紹一個MessageService,它要求用戶進行身份驗證才能訪問它。
 
public class HelloMessageService implements MessageService {

	@PreAuthorize("authenticated")
	public String getMessage() {
		Authentication authentication = SecurityContextHolder.getContext()
															.getAuthentication();
		return "Hello " + authentication;
	}
}

The result of getMessage is a String saying "Hello" to the current Spring Security Authentication. An example of the output is displayed below.安全

getMessage的結果是一個String,表示當前Spring Security Authentication的「Hello」。輸出的示例以下所示。
 
Hello org.springframework.security.authentication.UsernamePasswordAuthenticationToken@ca25360: Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER

11.1 Security Test Setup

Before we can use Spring Security Test support, we must perform some setup. An example can be seen below:app

在咱們使用Spring Security Test支持以前,咱們必須執行一些設置。下面是一個例子:
 
@RunWith(SpringJUnit4ClassRunner.class) 1
@ContextConfiguration 2
public class WithMockUserTests {

This is a basic example of how to setup Spring Security Test. The highlights are:ide

這是如何設置Spring Security Test的基本示例。亮點是:
 
一、@RunWith instructs the spring-test module that it should create an  ApplicationContext. This is no different than using the existing Spring Test support. For additional information, refer to the  Spring Reference
@RunWith指示spring-test模塊應該建立一個ApplicationContext。這與使用現有的Spring Test支持沒什麼不一樣。有關其餘信息,請參閱Spring Reference
二、@ContextConfiguration instructs the spring-test the configuration to use to create the  ApplicationContext. Since no configuration is specified, the default configuration locations will be tried. This is no different than using the existing Spring Test support. For additional information, refer to the  Spring Reference
@ContextConfiguration指示spring-test用於建立ApplicationContext的配置。因爲未指定任何配置,所以將嘗試使用默認配置位置。這與使用現有的Spring Test支持沒什麼不一樣。有關其餘信息,請參閱Spring Reference
 
Spring Security hooks into Spring Test support using the  WithSecurityContextTestExecutionListener which will ensure our tests are ran with the correct user. It does this by populating the  SecurityContextHolder prior to running our tests. After the test is done, it will clear out the  SecurityContextHolder. If you only need Spring Security related support, you can replace  @ContextConfiguration with  @SecurityTestExecutionListeners.
Spring Security使用WithSecurityContextTestExecutionListener掛鉤到Spring Test支持,這將確保咱們的測試是使用正確的用戶運行的。它經過在運行咱們的測試以前填充SecurityContextHolder來實現。測試完成後,它將清除SecurityContextHolder。若是您只須要與Spring Security相關的支持,則可使用@SecurityTestExecutionListeners替換@ContextConfiguration。
 
Remember we added the  @PreAuthorize annotation to our  HelloMessageService and so it requires an authenticated user to invoke it. If we ran the following test, we would expect the following test will pass:
請記住,咱們將@PreAuthorize註釋添加到HelloMessageService中,所以須要通過身份驗證的用戶才能調用它。若是咱們運行如下測試,咱們但願如下測試經過:
 
@Test(expected = AuthenticationCredentialsNotFoundException.class)
public void getMessageUnauthenticated() {
	messageService.getMessage();
}

11.2 @WithMockUser

The question is "How could we most easily run the test as a specific user?" The answer is to use @WithMockUser. The following test will be run as a user with the username "user", the password "password", and the roles "ROLE_USER".測試

問題是「做爲特定用戶,咱們怎樣才能最輕鬆地運行測試?」答案是使用@WithMockUser。如下測試將以用戶名「user」,密碼「password」和角色「ROLE_USER」的用戶身份運行。
 
@Test
@WithMockUser
public void getMessageWithMockUser() {
String message = messageService.getMessage();
...
}

Specifically the following is true:flex

具體以下:
 
  • The user with the username "user" does not have to exist since we are mocking the user
  • 用戶名爲「user」的用戶沒必要存在,由於咱們正在模擬用戶
  • The Authentication that is populated in the SecurityContext is of type UsernamePasswordAuthenticationToken
  • SecurityContext中填充的身份驗證的類型爲UsernamePasswordAuthenticationToken
  • The principal on the Authentication is Spring Security’s User object
  • 身份驗證的主體是Spring Security的User對象
  • The User will have the username of "user", the password "password", and a single GrantedAuthority named "ROLE_USER" is used.
  • 用戶將擁有「user」的用戶名,密碼「password」,並使用名爲「ROLE_USER」的單個GrantedAuthority。

Our example is nice because we are able to leverage a lot of defaults. What if we wanted to run the test with a different username? The following test would run with the username "customUser". Again, the user does not need to actually exist.ui

咱們的例子很好,由於咱們可以利用不少默認值。若是咱們想用不一樣的用戶名運行測試怎麼辦?如下測試將使用用戶名「customUser」運行。一樣,用戶不須要實際存在。
@Test
@WithMockUser("customUsername")
public void getMessageWithMockUserCustomUsername() {
	String message = messageService.getMessage();
...
}

We can also easily customize the roles. For example, this test will be invoked with the username "admin" and the roles "ROLE_USER" and "ROLE_ADMIN".this

咱們還能夠輕鬆自定義角色。例如,將使用用戶名「admin」和角色「ROLE_USER」和「ROLE_ADMIN」調用此測試。
@Test
@WithMockUser(username="admin",roles={"USER","ADMIN"})
public void getMessageWithMockUserCustomUser() {
	String message = messageService.getMessage();
	...
}

If we do not want the value to automatically be prefixed with ROLE_ we can leverage the authorities attribute. For example, this test will be invoked with the username "admin" and the authorities "USER" and "ADMIN".

若是咱們不但願值自動以ROLE_爲前綴,咱們能夠利用authority屬性。例如,將使用用戶名「admin」和權限「USER」和「ADMIN」調用此測試。
 
@Test
@WithMockUser(username = "admin", authorities = { "ADMIN", "USER" })
public void getMessageWithMockUserCustomAuthorities() {
	String message = messageService.getMessage();
	...
}

Of course it can be a bit tedious placing the annotation on every test method. Instead, we can place the annotation at the class level and every test will use the specified user. For example, the following would run every test with a user with the username "admin", the password "password", and the roles "ROLE_USER" and "ROLE_ADMIN".

固然,在每一個測試方法上放置註釋可能有點單調乏味。相反,咱們能夠將註釋放在類級別,每一個測試都將使用指定的用戶。例如,如下內容將使用用戶名爲「admin」,密碼爲「password」以及角色「ROLE_USER」和「ROLE_ADMIN」的用戶運行每一個測試。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WithMockUser(username="admin",roles={"USER","ADMIN"})
public class WithMockUserTests {

11.3 @WithAnonymousUser

Using @WithAnonymousUser allows running as an anonymous user. This is especially convenient when you wish to run most of your tests with a specific user, but want to run a few tests as an anonymous user. For example, the following will run withMockUser1 and withMockUser2 using @WithMockUser and anonymous as an anonymous user.

使用@WithAnonymousUser容許以匿名用戶身份運行。當您但願與特定用戶運行大多數測試但但願以匿名用戶身份運行一些測試時,這尤爲方便。例如,如下將使用@WithMockUser和匿名用戶匿名用戶運行withMockUser1和withMockUser2。
@RunWith(SpringJUnit4ClassRunner.class)
@WithMockUser
public class WithUserClassLevelAuthenticationTests {

	@Test
	public void withMockUser1() {
	}

	@Test
	public void withMockUser2() {
	}

	@Test
	@WithAnonymousUser
	public void anonymous() throws Exception {
		// override default to run as anonymous user
	}
}

11.4 @WithUserDetails

While @WithMockUser is a very convenient way to get started, it may not work in all instances. For example, it is common for applications to expect that the Authentication principal be of a specific type. This is done so that the application can refer to the principal as the custom type and reduce coupling on Spring Security.

雖然@WithMockUser是一種很是方便的入門方式,但它可能沒法在全部實例中使用。例如,應用程序一般指望Authentication主體具備特定類型。這樣作是爲了使應用程序能夠將主體稱爲自定義類型並減小Spring Security上的耦合。
 
The custom principal is often times returned by a custom  UserDetailsService that returns an object that implements both  UserDetails and the custom type. For situations like this, it is useful to create the test user using the custom  UserDetailsService. That is exactly what  @WithUserDetails does.
自定義主體一般由自定義UserDetailsS​​ervice返回,該自定義UserDetailsS​​ervice返回實現UserDetails和自定義類型的對象。對於這種狀況,使用自定義UserDetailsS​​ervice建立測試用戶頗有用。這正是@WithUserDetails所作的。
 
Assuming we have a  UserDetailsService exposed as a bean, the following test will be invoked with an  Authentication of type  UsernamePasswordAuthenticationToken and a principal that is returned from the  UserDetailsService with the username of "user".
假設咱們將UserDetailsS​​ervice公開爲bean,將使用UsernamePasswordAuthenticationToken類型的Authentication和從UserDetailsS​​ervice返回的用戶名爲「user」的主體調用如下測試。
@Test
@WithUserDetails
public void getMessageWithUserDetails() {
	String message = messageService.getMessage();
	...
}

We can also customize the username used to lookup the user from our UserDetailsService. For example, this test would be executed with a principal that is returned from the UserDetailsService with the username of "customUsername".

咱們還能夠自定義用於從UserDetailsS​​ervice查找用戶的用戶名。例如,此測試將使用從UserDetailsS​​ervice返回的主體執行,其用戶名爲「customUsername」。
 
@Test
@WithUserDetails("customUsername")
public void getMessageWithUserDetailsCustomUsername() {
	String message = messageService.getMessage();
	...
}

We can also provide an explicit bean name to look up the UserDetailsService. For example, this test would look up the username of "customUsername" using the UserDetailsService with the bean name "myUserDetailsService".

咱們還能夠提供一個顯式bean名稱來查找UserDetailsS​​ervice。例如,此測試將使用具備bean名稱「myUserDetailsS​​ervice」的UserDetailsS​​ervice查找「customUsername」的用戶名。
@Test
@WithUserDetails(value="customUsername", userDetailsServiceBeanName="myUserDetailsService")
public void getMessageWithUserDetailsServiceBeanName() {
	String message = messageService.getMessage();
	...
}

Like @WithMockUser we can also place our annotation at the class level so that every test uses the same user. However unlike @WithMockUser@WithUserDetailsrequires the user to exist.

與@WithMockUser同樣,咱們也能夠將咱們的註釋放在類級別,以便每一個測試都使用相同的用戶。可是,與@WithMockUser不一樣,@ WithUserDetails要求用戶存在。

11.5 @WithSecurityContext

We have seen that @WithMockUser is an excellent choice if we are not using a custom Authentication principal. Next we discovered that @WithUserDetails would allow us to use a custom UserDetailsService to create our Authentication principal but required the user to exist. We will now see an option that allows the most flexibility.

咱們已經看到,若是咱們不使用自定義身份驗證主體,@ WinMockUser是一個很好的選擇。接下來咱們發現@WithUserDetails將容許咱們使用自定義UserDetailsS​​ervice來建立咱們的身份驗證主體,但要求用戶存在。咱們如今將看到一個容許最大靈活性的選項。
 
We can create our own annotation that uses the  @WithSecurityContext to create any  SecurityContext we want. For example, we might create an annotation named  @WithMockCustomUser as shown below:
咱們能夠建立本身的註釋,使用@WithSecurityContext建立咱們想要的任何SecurityContext。例如,咱們可能會建立一個名爲@WithMockCustomUser的註釋,以下所示:
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class)
public @interface WithMockCustomUser {

	String username() default "rob";

	String name() default "Rob Winch";
}

You can see that @WithMockCustomUser is annotated with the @WithSecurityContext annotation. This is what signals to Spring Security Test support that we intend to create a SecurityContext for the test. The @WithSecurityContext annotation requires we specify a SecurityContextFactory that will create a new SecurityContext given our @WithMockCustomUser annotation. You can find our WithMockCustomUserSecurityContextFactory implementation below:

您能夠看到@WithMockCustomUser使用@WithSecurityContext註釋進行註釋。這是向Spring Security Test支持的信號,咱們打算爲測試建立SecurityContext。 @WithSecurityContext註釋要求咱們指定一個SecurityContextFactory,它將在給定@WithMockCustomUser註釋的狀況下建立一個新的SecurityContext。您能夠在下面找到咱們的WithMockCustomUserSecurityContextFactory實現:
public class WithMockCustomUserSecurityContextFactory
	implements WithSecurityContextFactory<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;
	}
}

 We can now annotate a test class or a test method with our new annotation and Spring Security’s WithSecurityContextTestExecutionListener will ensure that our SecurityContext is populated appropriately.

咱們如今可使用咱們的新註釋來註釋測試類或測試方法,Spring Security的WithSecurityContextTestExecutionListener將確保咱們的SecurityContext被適當地填充。
 
When creating your own  WithSecurityContextFactory implementations, it is nice to know that they can be annotated with standard Spring annotations. For example, the  WithUserDetailsSecurityContextFactory uses the  @Autowired annotation to acquire the  UserDetailsService:
在建立本身的WithSecurityContextFactory實現時,很高興知道它們可使用標準的Spring註釋進行註釋。例如,WithUserDetailsS​​ecurityContextFactory使用@Autowired批註獲取UserDetailsS​​ervice:
 
final class WithUserDetailsSecurityContextFactory
	implements WithSecurityContextFactory<WithUserDetails> {

	private UserDetailsService userDetailsService;

	@Autowired
	public WithUserDetailsSecurityContextFactory(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	public SecurityContext createSecurityContext(WithUserDetails withUser) {
		String username = withUser.value();
		Assert.hasLength(username, "value() must be non-empty String");
		UserDetails principal = userDetailsService.loadUserByUsername(username);
		Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(), principal.getAuthorities());
		SecurityContext context = SecurityContextHolder.createEmptyContext();
		context.setAuthentication(authentication);
		return context;
	}
}

11.6 Test Meta Annotations

If you reuse the same user within your tests often, it is not ideal to have to repeatedly specify the attributes. For example, if there are many tests related to an administrative user with the username "admin" and the roles ROLE_USER and ROLE_ADMIN you would have to write:

若是常常在測試中重複使用同一個用戶,則沒必要重複指定屬性。例如,若是有許多與用戶名爲「admin」且角色爲ROLE_USER和ROLE_ADMIN的管理用戶相關的測試,則必須編寫:
@WithMockUser(username="admin",roles={"USER","ADMIN"})

Rather than repeating this everywhere, we can use a meta annotation. For example, we could create a meta annotation named WithMockAdmin:

咱們可使用元註釋,而不是在任何地方重複這一點。例如,咱們能夠建立一個名爲WithMockAdmin的元註釋:
@Retention(RetentionPolicy.RUNTIME)
@WithMockUser(value="rob",roles="ADMIN")
public @interface WithMockAdmin { }

Now we can use @WithMockAdmin in the same way as the more verbose @WithMockUser.

如今咱們能夠像更詳細的@WithMockUser同樣使用@WithMockAdmin。

Meta annotations work with any of the testing annotations described above. For example, this means we could create a meta annotation for @WithUserDetails("admin") as well.

元註釋適用於上述任何測試註釋。例如,這意味着咱們也能夠爲@WithUserDetails(「admin」)建立元註釋。
相關文章
相關標籤/搜索