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?
You may be able to use
SpringSecurityUtils.reauthenticate username, null
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With