I'm having some problems testing a Spgring Boot 2 app using Spring Security 5.1.
Problem: I'm always getting a 403 on the response.
Here are the two approaches I've tried:
1) Disable security for testing by doing:
@Value("${security.enabled:true}")
private boolean securityEnabled;
@Override
protected void configure(HttpSecurity pHttpSecurity) throws Exception
{
if (!securityEnabled)
{
return;
}
And using an application.properties only for testing with this variable set to false. This still leads to 403 since PreAuthorize still wants you to be authorized and I've observed same behaviour when disabling security configuration in the past: I had to also comment out all PreAuthorize annotations to manually test without secutrity.
2) Running the test with:
@WithMockUser(username = "admin", roles = "ADMIN")
This solution actually poses a problem which is that PreAuthorize doesn't append automatically the ROLE_ prefix and this was actually the reason I was using it since my roles didn't have it either. For trying to make the test run I actually changed that for the routes I'm accessing and, if that's the only way of working, I'll change the role names (but then maybe @Secured will do the trick also).
This is how the relevant part of the request looks like when using @WithMockUser.
MockHttpServletRequest:
HTTP Method = POST
Request URI = /admin/createUser
Parameters = {}
Headers = {Content-Type=[application/json]}
Body = <no character encoding set>
Session Attrs = {SPRING_SECURITY_CONTEXT=org.springframework.security.core.context.SecurityContextImpl@e0791834:
Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@e0791834:
Principal: org.springframework.security.core.userdetails.User@586034f:
Username: admin; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true;
credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN;
Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_ADMIN}
I've also tried @Secured and @RolesAllowed with and without appending ROLE_ and same behaviour. None of the answers proposed in other similar posts worked so far.
So, any help on what I am doing wrong? Any way of proper testing with security enabled? If not, any way of telling Spring to ignore PreAuthorize if security is disabled?
Thanks in advance!
For future visitors, and much thanks to this guy who I found in the related posts of this one (but not by searching it before >.<) with the exact same problem:
Basically I had to add .with(csrf())
mvc.perform(post("/admin/createUser").with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(jsonNode.toString()))
.andExpect(status().isOk());