I've been attempting to log in a user automatically after a successful signup using grails with the spring-security-core plugin. While the forced login works, and all the authorities etc. are loaded, the @Secured annotations in other controllers won't recognise the granted authorities and consequently the browser gets stuck in a redirect loop between the secured and login pages.
My login action:
def forceLogin = {
PSysuser sysuser = flash.sysuser;
String username = flash.username ?: params.username;
String password = flash.password ?: params.password;
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
sysuser?.username ?: username,
sysuser?.password ?: password
);
request.session;
token.details = new WebAuthenticationDetails(request);
Authentication authenticatedUser = authenticationManager.authenticate(token);
SecurityContextHolder.context.authentication = authenticatedUser;
springSecurityService.reauthenticate(username, password); //doesn't appear to work, but doesn't hurt either.
redirect action:auth;
}
Does anyone know how I can get the annotations to work properly?
If you are using the spring-security-plugin, take a look at some of the helper classes . More specifically, check out the reauthenticate method of the SpringSecurityService. Here is an example from Burt's amazing documentation:
class UserController {
def springSecurityService
def update = {
def userInstance = User.get(params.id)
params.salt = person.salt
if (userInstance.password != params.password) {
params.password = springSecurityService.encodePassword(params.password, salt)
def salt = … // e.g. randomly generated using some utility method
params.salt = salt
}
userInstance.properties = params
if (!userInstance.save(flush: true)) {
render view: 'edit', model: [userInstance: userInstance]
return
}
if (springSecurityService.loggedIn &&
springSecurityService.principal.username == userInstance.username) {
springSecurityService.reauthenticate userInstance.username
}
flash.message = "The user was updated"
redirect action: show, id: userInstance.id
}
}
So, turns out that it wasn't the @Secured annotations at all, but the session-based authentication code left over from before spring-security was implemented. After adding the correct object to the session scope, the problem went away.
ARGH!
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.