简体   繁体   中英

How to switch user using Spring in Java for testing purposes?

I wrote functionality using Spring Security SwitchUserFilter . In application I can switch user using /j_spring_security_switch_user?j_username=xxx URL and go back to previous using /j_spring_security_exit_user . I also implemented several methods that depends on fact of switching user, so I want to write unit tests for them. Therefore my question is how can I switch user in jUnit tests environment?

I wrote method which is preparing user with SwitchUserGrantedAuthority and log him in. It seems working fine for my testing purposes, but any tips and comments would be very appreciated.

@SuppressWarnings({ "rawtypes", "unchecked" })
private User logAdminAsUser(User admin, String roleName) {
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(admin, null, "ROLE_ADMIN"));
    Authentication adminAuth = SecurityContextHolder.getContext().getAuthentication();
    SwitchUserGrantedAuthority switchUserGrantedAuthority =
        new SwitchUserGrantedAuthority("ROLE_ADMIN", adminAuth);
    List authorities = new LinkedList();
    authorities.add(switchUserGrantedAuthority);
    User user = populator.storeUser("ROLE_USER");
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(user, null, authorities));
    return user;
}

If you want an integrational test, you should consider using a custom http client, or if your test logic depends on it, even GUI drivers like Selenium.

If we are talking about unit tests, refer to Springs http://spring.io/blog/2014/05/07/preview-spring-security-test-method-security documentation, they support testing heavily, @WithMockUser annotation appears to be what you are looking for, it allows you to specify with which role or user this test should be runned.

I used this:

private void switchUser(User user, String roleName) 
{
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    Collection<GrantedAuthority> authorities = 
            new ArrayList<>();
    GrantedAuthority ga = new SimpleGrantedAuthority(roleName);
    authorities.add(ga);

    Authentication result = new UsernamePasswordAuthenticationTokenExt(
            user,
            authentication.getCredentials(),
            null,
            System.currentTimeMillis()
    );

    SecurityContextHolder.getContext().setAuthentication( result );
}

where User is the new user, and the roleName is the new authority to set (of course this method can be modified get more params, etc.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM