开发者

Why won't @Secured annotations work after a grails spring-security manual login?

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开发者_C百科 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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜