Reputation: 2339
How to prevent Spring Security from throwing AuthenticationCredentialsNotFoundException
in my unit tests? I'd like the user not to be authenticated, or to be authenticated anonymously.
I tried to do it like this:
SecurityContext ctx = SecurityContextHolder.createEmptyContext();
SecurityContextHolder.setContext(ctx);
// ctx.setAuthentication();
but I don't know where to get that anonymous authentication object from.
Upvotes: 1
Views: 2109
Reputation:
Your code example is very unspecific. I assume that you are using a basic configuration taken from Spring Security getting started page
To authenticate a user anonymously you will need to put an anonymous user into the security context:
SecurityContext ctx = SecurityContextHolder.createEmptyContext();
SecurityContextHolder.setContext(ctx);
ctx.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "", Arrays.asList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))));
Otherwise you should remove all security mappings or annotations from your relevant urls. See:
Upvotes: 4