Reputation: 301
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?
Upvotes: 10
Views: 4375
Reputation: 2621
You may be able to use
SpringSecurityUtils.reauthenticate username, null
Upvotes: 5
Reputation: 10938
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);
Upvotes: 4