title: Spring Boot Webflux Security - reading Principal in service class when writing tests
body: <p>I am quite new to the Spring ecosystem in general and Webflux. There are 2 things that I am trying to figure out and cannot find any specifics about.</p>
  
  <p><strong>My Setup:</strong></p>
  
  <p>I am writing a Spring Boot 2 REST API using WebFlux (not using controllers but rather handler functions). The authentication server is a separate service which issues JWT tokens and those get attached to each request as Authentication headers. Here is a simple example of a request method:</p>
  
  <pre><code>public Mono&lt;ServerResponse&gt; all(ServerRequest serverRequest) {
          return principal(serverRequest).flatMap(principal -&gt;
                  ReactiveResponses.listResponse(this.projectService.all(principal)));
      }
  </code></pre>
  
  <p>Which i use to react to a GET request for a list of all "Projects" that a user has access to. </p>
  
  <p>I afterwards have a service which retrieves the list of projects for this user and i render a json response.</p>
  
  <p><strong>The Problems:</strong></p>
  
  <p>Now in order to filter the projects based on the current user id i need to read it from the request principal. One issue here is that i have plenty service methods which need the current user information and passing it through to the service seems like an overkill. One solution is to read the principal inside the service from:</p>
  
  <p><code>Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();</code></p>
  
  <p><strong>Question 1:</strong></p>
  
  <p>Is this a good practice in general when writing functional code (If i do this instead of propagating the principal)? is this a good approach despite the complexity of reading and sending the principal from the request to the service in each method?</p>
  
  <p><strong>Question 2:</strong></p>
  
  <p>Should i instead use the SecurityContextHolder Thread Local to fetch the principal, and if i do that how do i write tests for my service?</p>
  
  <p>If i use the Security Context how do i test my service implementations which are expecting a principal that is of type <code>JWTAuthenticationToken</code>  <a href="https://i.stack.imgur.com/fGvG7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fGvG7.png" alt="JWTAuthenticationToken"></a></p>
  
  <p>and i always get <code>null</code> when trying to do something like described here: <a href="https://stackoverflow.com/questions/360520/unit-testing-with-spring-security">Unit testing with Spring Security</a></p>
  
  <p>In the service tests, In tests what i've managed to do so far is to propagate the principal to the service methods and use mockito to mock the principal. This is quite straightforward.
  In the Endpoint Tests i am using <code>@WithMockUser</code> to populate the principal when doing requests and i mock out the service layer. This has the downside of the principal type being different.</p>
  
  <p>Here is how my test class for the service layer looks:</p>
  
  <pre><code>@DataMongoTest
  @Import({ProjectServiceImpl.class})
  class ProjectServiceImplTest extends BaseServiceTest {
  
      @Autowired
      ProjectServiceImpl projectService;
  
      @Autowired
      ProjectRepository projectRepository;
  
      @Mock
      Principal principal;
  
      @Mock
      Principal principal2;
  
      @BeforeEach
      void setUp() {
          initMocks(this);
  
          when(principal.getName()).thenReturn("uuid");
          when(principal2.getName()).thenReturn("uuid2");
      }
  
      // Cleaned for brevity 
  
      @Test
      public void all_returnsOnlyOwnedProjects() {
          Flux&lt;Project&gt; saved = projectRepository.saveAll(
                  Flux.just(
                          new Project(null, "First", "uuid"),
                          new Project(null, "Second", "uuid2"),
                          new Project(null, "Third", "uuid3")
                  )
          );
          Flux&lt;Project&gt; all = projectService.all(principal2);
          Flux&lt;Project&gt; composite = saved.thenMany(all);
  
          StepVerifier
                  .create(composite)
                  .consumeNextWith(project -&gt; {
                      assertThat(project.getOwnerUserId()).isEqualTo("uuid2");
                  })
                  .verifyComplete();
      }
  
  }
  </code></pre>