In the previous blog post, we discussed how to configure a simple OAuth2 authentication. However, our implementation has a major flaw in it: we are using an in-memory token store.

In-Memory token stores should be used only during development or whether your application has a single server, as you can’t easily share them between nodes and, in case of a server restart, you will lose all access tokens in it.

Spring-security-oauth2 already has built-in support for JDBC and JWT. However, if you need to save your tokens somewhere else, you have to create your own spring security token store. Unfortunately, implementing such a thing is not a trivial task, and I hope the following recipe will save you a couple hours of work.

Let’s start by creating the two entities responsible for storing your access and refresh token, and their respective repositories:

 

 

 

 

Note that OAuth2Authentication is an interface, so I have no option other than serializing the object to store it in the database. Here is the class responsible for serializing/deserializing it:

 

Now, we can finally create our custom spring oauth2 token store. To do that, all we need is to implement the long list of methods of the org.springframework.security.oauth2.provider.token.TokenStore:

 

Finally, we can slightly change our SecurityConfig class, which we have created in the previous article. It will return now an instance of CouchbaseTokenStore instead of InMemoryTokenStore:

 

Here is the complete version of the SecurityConfig class:

 

Well Done! That is all we had to do.

Your access token will look like the following in your database:

 

I have used caelwinner’s project as a reference, here is my special thanks to him.

If you have any questions, feel free to tweet me at @deniswsrosa

 

 

Author

Posted by Denis Rosa, Developer Advocate, Couchbase

Denis Rosa is a Developer Advocate for Couchbase and lives in Munich - Germany. He has a solid experience as a software engineer and speaks fluently Java, Python, Scala and Javascript. Denis likes to write about search, Big Data, AI, Microservices and everything else that would help developers to make a beautiful, faster, stable and scalable app.

One Comment

  1. Hi Denis,
    First of all, thank you for the very brief but concise tutorial. Although it is over a year, it is well explained, and I must acknowledge that you are an excellent teacher.
    Please, I have one question and a request to make. Is it possible to add JWT to this implementation OAuth2, and if yes,can you please provide a guide?
    Waiting for a reply.
    Thank you so much.

Leave a reply