Search code examples
springgrailsspring-securitybootstrapping

Log in a user at application start up


I am using latest Grails and the spring security plugin. I would like to log in a predefined guest user at application start up but not sure how to achieve this.

  1. How do I programmatically log in a user? (I'm attempting this in bootstrap but can not find what to import for the AuthToken class)
  2. Where is this best done - i.e. in the bootstrap config?

Solution

  • Okay I found a solution... it's a bit raw, and I'm not sure this is the best place for it at application startup, but it achieves what I wanted.

    So in Bootstrap file I have implemented the following:

    Here's my imports:-

    import grails.plugin.springsecurity.rest.token.AccessToken
    import grails.plugin.springsecurity.rest.token.generation.TokenGenerator
    import org.springframework.security.authentication.AuthenticationManager
    import org.springframework.security.authentication.BadCredentialsException
    import org.springframework.security.core.Authentication
    import org.springframework.security.core.context.SecurityContextHolder
    import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
    import org.springframework.security.core.userdetails.UserDetails
    

    ...after all bootstrapping of my user I want to auto log in a Guest user and then generate the JWT refresh and access token too...

        /* Login in guest user on application startup */
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("guest", "guest");
        token.setDetails(tttGuest);
        try {
            //doing actual authentication
            Authentication auth = authenticationManager.authenticate(token);
            log.debug("Login succeeded!");
            //setting principal in context
            SecurityContextHolder.getContext().setAuthentication(auth);
    
            //Generate JWT access token and refresh token
            AccessToken accessToken = tokenGenerator.generateAccessToken(springSecurityService.principal as UserDetails)
    
            return true
        } catch (BadCredentialsException e) {
            log.debug("Login failed")
            return false
        }
    

    The only part left to do is to figure out how to communicated the tokens back to the client application.