Skip to content
Advertisement

Why my test passes without a bearer token

I have a simple Spring app. But I don’t understand why the test passes without the need of a bearer token.

Here is the controller:

JavaScript

Security Configuration:

JavaScript

In order to setup the security configs for tests I’m using:

JavaScript

So my test class looks like this:

JavaScript

If I change the autority in the test to something like ‘foo-user’ the response becomes 403, as expected, and because of that I think that the security configuration is being applied.

If I test the application with Postman the bearer token is needed to run requests, but why its not needed in the test?

Advertisement

Answer

@WithMockUser annotation does not do authentication. (Please note, you even did not provide a user name.) It creates a new default user with user/password name and passwords and this user is authenticated already with a UsernamePasswordAuthenticationToken. And you provided the authority for this default user/password user in your @WithMockUser(authorities = “app-user”) annotation as “app-user”. https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/test/context/support/WithMockUser.html

So the user you run your test has authentication and authorization.

Your security configuration is NOT being applied. Again, @WithMockUser creates new empty security context with SecurityContextHolder.createEmptyContext() with security defaults. https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/test/context/support/WithMockUser.html

And when you use Postman all that does not happen of course and you real user must be authenticated with normal bearer token.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement