Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to authenticate user against spring Security in unit tests

I am using spring security core plugin (1.2.7) with grails 2.0

Let's say that I have controller with a method that uses @Secured annotation.

class ArticleController {
    def springSecurityService

    @Secured(['ROLE_PREMIUM_USER'])
    def listPremium() { 
        render 'premium content'
    }
}

in my unit test I would like to test if a user with role 'ROLE_PREMIUM_USER' can see content of listPremium method. How can I do this?

I know that it should start as follows:

@TestFor(ArticleController)
@Mock([SpringSecurityService])
class ArticleControllerTests {
    void testListPremium() {
    defineBeans {
        springSecurityService(SpringSecurityService)
    }
         //but how to login the user here in order to see premium content?

        controller.listPremium()
        assert response.text() == 'premium content'
    }
}

I am not sure how can I authenticate user or mock action that checks ROLE_PREMIUM_USER. Any help?

like image 452
Bart Avatar asked May 08 '12 23:05

Bart


2 Answers

You may be able to use

SpringSecurityUtils.reauthenticate username, null
like image 62
chrislovecnm Avatar answered Oct 14 '22 11:10

chrislovecnm


We created our custom AuthenticationHelper:

public final class AuthenticationHelper {

    public static Authentication authenticate(UserDetailsService userDetailsServiceImpl, String userName) {

        UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(userName);

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword());

        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(userDetails, token.getCredentials(), userDetails.getAuthorities());
        result.setDetails(token.getDetails());
        Authentication auth = result;

        SecurityContextHolder.getContext().setAuthentication(auth);
        auth = SecurityContextHolder.getContext().getAuthentication();

        Assert.assertTrue(auth.isAuthenticated());

        return auth;
    }
}

The important part is:

SecurityContextHolder.getContext().setAuthentication(auth);
like image 41
Pete Avatar answered Oct 14 '22 10:10

Pete