Spring Boot and OAuth2 with JDBC

How can we implement OAuth2 with Spring Boot?

This blog post assumes that you know what is the OAuth2 protocol and how it works. If you do not know, I advise you to do some research and come back later as you may not fully understand it from reading this blog post.

There are several examples online but most of them are using some sort of in memory database. If your system is going to production you, most likely, do not want to use an in memory database to store the user tokens when you have multiple server instances. You want some sort of a central location (or distributed with some level of consistency) where you’ll be storing the OAuth data for each user account. The easiest is using a SQL database and this is going to be our example.

First, it’s time to setup the database tables for the OAuth2, therefore we need the following tables:

  • oauth_client_details
  • oauth_client_token
  • oauth_access_token
  • oauth_refresh_token
  • oauth_code
  • oauth_approvals
  • ClientDetails

As we are using Spring Boot we can create a file named schema.sql  in the resources folder with our schema definition. On boot time, Spring Boot will detect the file and will run it against our selected database – quite handy isn’t it?

When the database schema is all set, we need to populate the oauth_client_details table. Again, Spring Boot helps making our life easier. To do so, we just need to create a file named data.sql  and, as with the schema.sql , Spring Boot on boot time will pick the file and run in against our database.

At this point we have everything related with the SQL database ready to go.

Now, to the coding. We need to add the @EnableResourceServer annotation to our Spring application, and we do it as easy as:

@EnableResourceServer
@SpringBootApplication
public class OauthExampleApplication {

   public static void main(String[] args) {
      SpringApplication.run(OauthExampleApplication.class, args);
   }
}

The next step is to configure our DataStore  and our TokenStore . To do so we create an AppConfig.class  (wich is a configuration class) and define it there (you can define it somewhere else as long as you set the @Bean  annotation to both methods).

@Configuration
public class AppConfig {
    
    @Value("${spring.datasource.url}")
    private String datasourceUrl;
    
    @Value("${spring.database.driverClassName}")
    private String dbDriverClassName;
    
    @Value("${spring.datasource.username}")
    private String dbUsername;
    
    @Value("${spring.datasource.password}")
    private String dbPassword;
    
    @Bean
    public DataSource dataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        
        dataSource.setDriverClassName(dbDriverClassName);
        dataSource.setUrl(datasourceUrl);
        dataSource.setUsername(dbUsername);
        dataSource.setPassword(dbPassword);
        
        return dataSource;
    }
    
    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource());
    }
}

As we can see above, our TokenStore  is defined by a JdbcTokenStore  which extends TokenStore . We also pass the DataSource  to the JdbcTokenStore and therefore we let the application know we are using the specified DataSource  to store all our OAuth2 data. On the other hand, the DataSource  specifies that we are using a SQL database. See how it all interconnects here? Perfect.

But this is not enough. Now we need to wired everything up, the database – the authorization server – Spring Boot application. The authorization server will be the bridge here. So, lets start with it. We create a class (AuthServerOAuth2Config) to extend AuthorizationServerConfigurerAdapter . Then we need to override configure(ClientDetailsServiceConfigurer clients) , configure(AuthorizationServerSecurityConfigurer security) and configure(AuthorizationServerEndpointsConfigurer endpoints)  methods to wire everything up.

@EnableAuthorizationServer
@Configuration
public class AuthServerOAuth2Config extends AuthorizationServerConfigurerAdapter {
    
    private final AuthenticationManager authenticationManager;
    private final AppConfig appConfig;
    
    @Autowired
    public AuthServerOAuth2Config(AuthenticationManager authenticationManager, AppConfig appConfig) {
        this.authenticationManager = authenticationManager;
        this.appConfig = appConfig;
    }
    
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(appConfig.dataSource());
    }
    
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        /*
         * Allow our tokens to be delivered from our token access point as well as for tokens
         * to be validated from this point
         */
        security.checkTokenAccess("permitAll()");
    }
    
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .tokenStore(appConfig.tokenStore()); // Persist the tokens in the database
    }
}

And now we have OAuth2 with JDBC implemented. We can start generating some tokens by making POST requests to our server at /oauth/token with the Authorization type, headers and body (form data) properly set up.

Optionally we may want to create an endpoint that will return all information for the user calling it. To do so, we create the PrincipalResource.class  as shown below

@RestController
@RequestMapping(path = "/account")
public class PrincipalResource {

    @RequestMapping(method = RequestMethod.POST)
    public Principal oauth(Principal principal) {
        /*
         * Translate the incoming request, which has an access token
         * Spring security takes the incoming request and injects the Java Security Principal
         * The converter inside Spring Security will handle the to json method which the Spring Security
         * Oauth client will know how to read
         *
         * The @EnableResourceServer on the application entry point is what makes all this magic happen.
         * If there is an incoming request token it will check the token validity and handle it accordingly
         */
        return principal;
    }
}

Now, every time someone makes sends a GET request to /account with a valid token we return all known information about that person.

Enjoy your application server with support for OAuth2 using JDBC/SQL database.

PS; All source code can be found on my GitHub repository.

Software Engineering Podcasts

It can be hard to keep up  with what’s going on in the software engineering scene. To keep myself updated I normally spend my commute time listening to software engineering podcasts and today I’m going to share my list.

  • Fragmented Podcast, mostly Android related. From time to time, some general Java episodes. A must have for any Android developer out there.
  • Developer Tea, a podcast about web apps (mostly RoR and Javascript), soft skills and listener questions.
  • Software Engineering Daily, an all round podcast with daily episodes. Usually the focus is around frameworks, tools, big data, databases, programming languages and what not related to software engineering. A must have for any software engineer. They also have a very good newsletter, make sure you subscribe it.
  • The Change Log, another all round podcast. With episodes from frameworks, software architecture to unit testing and tools. Another must have for any software engineer.
  • Java Pub House, a more Java and Java EE focused podcast. Usually discussing Java and Java EE concepts, frameworks and APIs, like REST services, ThreadLocal and Spring Framework.
  • Software Engineering Radio, another all round podcast. Mostly featuring frameworks, tools, big data, programming languages and software architecture. A must have for any software engineer.
  • Soft Skills Engineering, a weekly podcast about soft skills for software engineers. A funny and easy to listen podcast. Recommended.
  • The Magpie Talkshow, a podcast by Sam Newman. Mostly interviews with well known and reputable software engineers.

 

Newly added to my list but yet to listen to an episode:

If you are on Android, I highly recommend you Pocket Casts as your podcast app. There is also a web app, which you can synchronize with the Android app.

This Week in Dev #9

This Week in Dev (TWiD) is a curated list with the most funny and interesting articles I stumble upon during my work and research time.

Java

  • Logging is a vital part in your software development daily life and Common Log4J Mistakes is a short and interesting read for every software developer out there.

Distributed Systems

General

Others

This Week in Dev #8

This Week in Dev (TWiD) is a curated list with the most funny and interesting articles I stumble upon during my work and research time.

This issue is more focused on DevOps, a hot trend at the moment.

  • Stackoverflow is one of the biggest sites on the internet. Such sites have more than one server. Deploying your new version can be tricky and hard to manage. Nick Craver, Software Developer and Systems Administrator at Stackoverflow, explains how Stackoverflow deploys to production.
  • Apache Mesos, a distributed systems kernel, abstracts your cluster of nodes into a single pool of resources. DC/OS is an enterprise grade datacenter scale operating system. Codecentric uploaded a short and entertaining video explaining What is DC/OS and Mesos?

Software Developer

  • Have you ever thought or are you curious to know how’s the life of a software developer after 40? Then this is an interesting read.
  • Bugs are the worst enemy for every software developer. We try as hard as we can to avoid them but sometimes they just pop out of nowhere. Still, are software developers the only ones dealing with bugs? No, not really.

Technology

 

And… that’s all folks. See you next week.

This Week in Dev #7

Welcome to the seventh issue of This Week in Dev.

Java

  • Sometimes you need to log the data access in our application. The problem comes when you are using a data access framework, like Hibernate, that uses PreparedStatement and the bound values are not logged. To bypass this issue, Vlad Mihalcea has an interesting article on the best way of logging JDBC statements.

General development

  • When to rewrite from scratch? Why, when and lessons learnt. Autopsy of a failed software. We all had that feeling of rewriting our product from scratch, before making a decision you should read this.

 

This is it folks, see you next week.

This Week in Dev #6

Welcome to another issue of TWID. This time it is a bit more relaxed but still an interesting one.

The JVM World

  • Sooner or later, every software engineer will stumble upon JSON. Some love it others don’t. If you hate it, you should give a try to Hjson, the Human JSON.

Scalability

Show Cases

  • Turn any website into an API with WrapAPI.

 

Time to say goodbye. Enjoy your week!

This Week in Dev #5

This week we have a rather short list, nevertheless still quite interesting.

  • Do you know Vert.x? It’s a very nice and intuitive toolkit to build reactive applications on the JVM. Check out what happens when Weld meets Vert.x.
  • Working solo or remote? Check out Kite, your virtual pair programming partner. Still missing some big IDEs names but the plugins are open source, feel free to improve or add your own plugin.
  • Writing email templates? Need inspiration? Check out Good Email Copy and get a peak where the email trend and design is heading to.

And last, but not least, check out this book parody by Practical Developer.

Time to say goodbye and see you next week.

This Week in Dev #4

Welcome to This Week in Dev #4. From now on TWID will be published at the beginning of the week.

Let’s begin with Docker.

Time to jump on the JVM world.

Meanwhile, on Android.

Time to wrap up…

And that’s it. See you next week.

 

 

This Week in Dev #3

Today we have a rather long “This Week in Dev”.


Baeldung.com explains the best ways to deal with bidirectional relationships with Jackson.

Are you new to Java 8 Completable Future or Async programming? You definitely have to watch this talk by José Paumard at Devoxx Belgium, Asynchronous Programming in Java 8: How to Use CompletableFuture.

Why you should be careful when working with phone numbers, Falsehoods Programmers Believe About Phone Numbers.

We all know how big is the Chinese market but did you know that it is so big that it has its own UI mobile trends?

For the StackOverflow fans out there that can’t make their job without it, did you know you now have a StackOverflow Autocomplete?

Filip Hracek shows why the famous “Hello World” is a fallacy.

Doing tech talks or presenting code to an audience? Check spectacle code slide and rock on those presentations.

Goroutines shows how you can handle 10 million concurrent connections using Go.

We all want to write good code, that is our ultimate goal.  has some tips on how to reduce the cognitive load of your code.

Planning on stepping on distributed systems? Wait no more, this introduction to distributed systems should warm you up.

Fan of graphs? Elastic has added Graph to data visualisation plug-in Kibana, Voxxed has short and concise article about it.

This should never happen, a funny and curious thread on Hackernews.

Bored? Fan of GTA San Adreas? Check this funny San Andreas Streaming Deer Cam streaming.


And that’s it for this week. Time to say goodbye and see you next week.

This Week in Dev #2

A bit late this week, Easter and holidays didn’t let me have that much free time. Here’s This Week in Dev issue number two.

Adam Bien has published another great video, The Overhead Of Java EE Application Servers.

Zero Turn Around has pulish another nice article on how to speed up your Maven builds. Meanwhile, you can also speed up your dependencies downloads.

Talking about dependencies and builds, check how one developer just broke Node, Babel and thousands of projects in 11 lines of JavaScript.

Still on the NPM, Kik debacle creates worst NPM mess ever.

Have you ever heard of Java 8 Optional? Here’s how to use it and say goodbye to those nasty null pointer exceptions.

What do you think about the JEP 286? Roy van Rijn explains the pros and cons of JEP 286.

Docker just announced they are in beta for Mac and Windows.

Lightbend (formerly known as Typesafe) is giving away a report about Reactive Microservices Architecture, by Lightbend CTO Jonas Bonér. Register to get your.

And finally, tehcnology is moving at a speed never seen before. Check this awesome video: Real-time Face Capture and Reenactment of RGB Videos.

See you next week.