View Javadoc
1   package org.imageconverter.controller.actuator;
2   
3   import java.io.UnsupportedEncodingException;
4   
5   import org.apache.commons.codec.binary.Base64;
6   import org.springframework.beans.factory.annotation.Autowired;
7   import org.springframework.boot.test.web.server.LocalManagementPort;
8   import org.springframework.boot.test.web.server.LocalServerPort;
9   import org.springframework.http.HttpHeaders;
10  import org.springframework.security.web.csrf.CsrfTokenRepository;
11  
12  /**
13   * Base class to test with csf.
14   * 
15   * @author Fernando Romulo da Silva
16   */
17  public class BaseTesseractHealthTest {
18  
19      @LocalServerPort
20      protected int serverPort;
21  
22      @LocalManagementPort
23      protected int managementPort;
24  
25      @Autowired
26      protected CsrfTokenRepository httpSessionCsrfTokenRepository;
27      
28      /**
29       * Create headers with basic authentication
30       * 
31       * @return A HttpHeaders object
32       * @throws UnsupportedEncodingException If something get wrong
33       */
34      protected HttpHeaders basicAuthHeaders() throws UnsupportedEncodingException {
35  	final var plainCreds = "user:password"; // application-test.yml-application.user_login: user
36  	final var plainCredsBytes = plainCreds.getBytes("UTF-8");
37  	final var base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
38  	final var base64Creds = new String(base64CredsBytes, "UTF-8");
39  
40  	final var headers = new HttpHeaders();
41  	headers.add("Authorization", "Basic " + base64Creds);
42  	return headers;
43      }
44  
45      /**
46       * Create headers with basic authentication with csrf
47       * 
48       * @return A HttpHeaders object
49       * @throws UnsupportedEncodingException If something get wrong
50       */
51      protected HttpHeaders csrfHeaders() throws UnsupportedEncodingException {
52  
53  	final var csrfToken = httpSessionCsrfTokenRepository.generateToken(null);
54  	final var headers = basicAuthHeaders();
55  
56  	headers.set("Content-Type", "application/json");
57  	headers.add(csrfToken.getHeaderName(), csrfToken.getToken());
58  	headers.add("Cookie", "XSRF-TOKEN=" + csrfToken.getToken());
59  
60  	return headers;
61      }
62  }