Adding MySQL Spring Security to Existing H2 App

I put NixMash Spring v0.1.6 on GitHub with H2Database Spring Security support only. MySQL is now supported and this post will cover the highlights, though as you’ll see there isn’t much to cover. All of NixMash Spring now supports both H2Database and MySQL. To switch between the two, simply change the Spring Active Profile in Gradle, on the Command Line, in, or in code.

The first issue was cleaning up the data table column names of Users, Authorities and User_Authorities in H2 to match a more standard MySQL column syntax. “id” became “user_id”, “firstname” became “first_name” (thus User.firstName rather than User.firstname), and a few other minor tweaks.

NixMash Spring was built from the ground-up to support both MySQL and H2, so after freshening-up the User and Authority model properties the only thing remaining was adding a MySQL data source in the Spring Security Configuration.

Since Spring Security was fully wired for H2, the ONLY bit of code we needed to add was a MySQL data source for user data. You’ll notice we’re leveraging Spring’s standard JDBC implementation of the UserDetailsService. We’re also using GlobalAuthenticationConfigurerAdapter instead of  WebSecurityConfigurerAdapter so we’re sure that initialization occurs before the authentication manager is needed elsewhere.

protected static class MySqlWebSecurityConfiguration extends
    GlobalAuthenticationConfigurerAdapter {

	private DataSource dataSource;

	public void init(AuthenticationManagerBuilder auth) throws Exception {
	    JdbcUserDetailsManager userDetailsService = new JdbcUserDetailsManager();
	    PasswordEncoder encoder = new BCryptPasswordEncoder();


In the previous paragraph I put “only” of “the ONLY code we needed” in caps because with the data source structures being similar, the shared Model nature of Spring JPA, and Spring Profiles, using so little code to add a new data source for User Authentication is pretty wild. You Young Bucks might not appreciate that, but us Old Timers do.