1

Here you have my controller method:

@PreAuthorize("principal == '" + EspaiDocConstants.BO_COMPONENT_APP + "'")
public void ingestAudits() {
    // Do something
}

As you can see, it's protected using @PreAuthorize("principal == '" + EspaiDocConstants.BO_COMPONENT_APP + "'")

Here my test code:

@WithMockUser(username=EspaiDocConstants.BO_COMPONENT_APP)
@Test
public void test() throws IOException, NoSuchAlgorithmException {
    this.controller.ingestAudits();
}

Nevertheless, I'm getting this exception message:

DigestAuditsTest.test:91 » AccessDenied Access is denied

EDIT

In order to populate principal, I'm using a custom filter:

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
    @Override
    protected void doFilterInternal(
        HttpServletRequest req,
        HttpServletResponse res,
        FilterChain chain
    ) throws IOException, ServletException {
        String user = Jwts.parser().setSigningKey(SECRET)
            .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
            .getBody().getSubject();

        SecurityContextHolder.getContext()
            .setAuthentication(
                new UsernamePasswordAuthenticationToken(user, null)
            );

        chain.doFilter(req, res);
    }
}

So, principal is an String containing user.

Besides of that, I'm not able to change this code right now, and I'd like to know how to provide a "String user" to principal using @WithMockUser.

Jordi
  • 20,868
  • 39
  • 149
  • 333

1 Answers1

0

You should verify only username, not whole principal object using "==".

@PreAuthorize("principal.username == '" + EspaiDocConstants.BO_COMPONENT_APP + "'")