Tag Archives: jdbc

Spring Security Auto Login After Successful Registration

Asking your user to login immediately after he/she registers might be tedious. Here’s how you can log them in immediately using Spring Security (thanks to this SO thread).

Typically you will have some sort of registration form with a backing controller like this:


("/register")
public class RegisterController {
  ...
  (method = POST)
  public String register( User user) {
    // perform registration logic..
    // redirect back to login page
    return "redirect:/login";
  }
  ...
}

But a server-side login can be done by autowiring UserDetailService and AuthenticationManager:


("/register")
public class RegisterController {
  ...
   ("authMgr") private AuthenticationManager authMgr;
   private UserDetailsService userDetailsSvc;

  (method = POST)
  public String register( User user) {
    // perform registration logic..

    // perform login authentication
    try {
      UserDetails userDetails = userDetailsSvc.loadUserByUsername(username);
      UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities());
      authMgr.authenticate(auth);

      // redirect into secured main page if authentication successful
      if(auth.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(auth);
        return "redirect:/";
      }
    } catch (Exception e) {
      logger.debug("Problem authenticating user" + username, e);
    }

    return "redirect:/error";
  }
  ...
}

Note that in above code the AuthenticationManager injection is qualified by ("authMgr"). This is to avoid multiple beans ambiguity. In effect in the xml context configuration (if you use one) an id attribute has to be set:

  ...
  
    ...
  

  
    ...
  
  ...

Also in order for this setup to work, the registration page has to be filtered by spring security

  ...
  
  

  
    
  
  ...

See Also

Installing Spring Security On Spring MVC Project

Tomcat 7 JDBC Session Persistence

The default Tomcat session management strategy is in-memory session persisted into file when the server is shutdown gracefully. If the server dies in a cold fashion (eg: kill -9 or power outage), session data might be lost. One approach to mitigate this is to store session data into database using JDBC, aka JDBC Session Persistence.

JDBC Session Persistence can also aid load balancer failover scenario. I’d say this is an alternative to setting up (often cumbersome) TCP session replication. Note that if you have multiple cloud servers like Amazon EC2 it doesn’t come with TCP multicast feature — TCP session replication sounds like a nightmare to setup.

The Steps

  1. Ensure org.apache.catalina.session.StandardSession.ACTIVITY_CHECK or org.apache.catalina.STRICT_SERVLET_COMPLIANCE is set to true. Add line similar to following into your Tomcat’s startup.sh (if you’re on UNIX)
    export CATALINA_OPTS="-Dorg.apache.catalina.session.StandardSession.ACTIVITY_CHECK=true"

    Tomcat System Property Reference will explain what do each property means if you’re curious

  2. Create following SQL table (yes you need a database to store the session data)
    create table tomcat_sessions (
      session_id     varchar(100) not null primary key,
      valid_session  char(1) not null,
      max_inactive   int not null,
      last_access    bigint not null,
      app_name       varchar(255),
      session_data   mediumblob,
      KEY kapp_name(app_name)
    );
    
  3. Place a copy of mysql-connector-java.jar (or your DB’s JDBC driver) into $CATALINA_HOME/lib
  4. In your web app, add a META-INF/context.xml file. If you use standard maven layout you have to place it on src/main/webapp/META-INF/context.xml. You can copy the file from $CATALINA_HOME/conf/context.xml as a starting point. Then under element add following element
    
      
    
    

    Notice how the SQL column name corresponds to some of the settings above. In this configuration I used mysql database on localhost with database name “mytomcat” and username “root”. maxIdleBackup=”10″ specifies number of seconds before the in-memory session data is persisted into database.

    There are many other settings you can tweak, have a look at the Tomcat Manager Component Reference.

Fine Prints

This article is tested against Tomcat 7.0.39 but I guess it should also work with Tomcat 6. If you’ve jumped the ship from relational to MongoDB, . I haven’t got a chance to try it but it looks awesome.