Inject Authentication in SecurityContext for JUnit tests (Java+Spring)

254 Views Asked by At

I have a test method for serivice method. Service method has the next annotation:

@PreAuthorize("verifyRole(T(java.util.Set).of(" +
    "'ROLE_HEAD_BANK', 'ROLE_OPERATOR_BANK_REPORTER', 'ROLE_AUTHORIZED_BANK_REPORTER'," +
    " 'ROLE_AUTHORIZED_BANK_REPORTER', 'ROLE_OPERATOR_BANK_REPORTER'))")

Method verifyRole:

public boolean verifyRole(Set<String> roles) {
  var grantedAuthorities =
    ((User) authentication.getPrincipal()).getGrantedAuthorities()
    .stream()
    .map(GrantedAuthority::getAuthority)
    .collect(Collectors.toSet());

  return !Collections.disjoint(grantedAuthorities, roles);
}

I try to run my test method with @WithMockUser(roles = {"HEAD_BANK","AUTHORIZED_BANK_REPORTER"}) and it fails in verifyRole method on (User) authentication.getPrincipal() with the next error: java.lang.ClassCastException: class org.springframework.security.core.userdetails.User cannot be cast to class com.kilma.raw.domain.entity.User (org.springframework.security.core.userdetails.User and com.kilma.raw.domain.entity.User are in unnamed module of loader 'app')

I've tried different type of solving that moment and @WithMockUser the farest I could go. If there any other way to handle it please tell me? Maybe I need to work on SecurityContext but already tried and didn't work.

P.S. When I comment @PreAuthorize annotation everything works well.

My test code that fails on reportService.getReport, getReport method with @PreAuthorize annotation:

@Test
@WithMockUser(roles = {
  "HEAD_BANK",
  "AUTHORIZED_BANK_REPORTER"
})
void getReport_success() {
  final ReportResponse report = reportService.getReport(1 L, bank1MockedAuth).getPayload();

  final long publishedWithDataReportId = 1 L;
  assertEquals(publishedWithDataReportId, report.getId());
  final Instant instant = Instant.parse("2022-04-01T00:00:00.000Z");
  final Long testDate = instant.toEpochMilli();
  assertEquals(testDate, report.getCreatedAt());
  assertEquals(testDate, report.getModifiedAt());
  assertEquals(KEY_MORTGAGE_INDICATOR, report.getReportType());
  assertEquals(testDate, report.getReportPeriod());
  assertEquals(PUBLISHED, report.getStatus());
}      
0

There are 0 best solutions below