kboom
kboom

Reputation: 2339

Prevent AuthenticationCredentialsNotFoundException while unit-testing

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

Answers (1)

user3151168
user3151168

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:

How do I get permitAll in Spring Security to NOT throw AuthenticationCredentialsNotFoundException in @Controller object?

Upvotes: 4

Related Questions