1

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.

1 Answer 1

4

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.