모범 사례 및 튜토리얼

How to Create a Custom Token Store for Spring-Security-Oauth2 | OAuth Part 2

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

 

 

이 기사 공유하기

작가

데니스 로사(Denis Rosa)는 카우치베이스(Couchbase)의 개발자 애드보케이트이며 독일 뮌헨에 거주하고 있습니다. 그는 소프트웨어 엔지니어로서 탄탄한 경험을 가지고 있으며 자바, 파이썬, 스칼라, 자바스크립트를 유창하게 구사합니다. 데니스는 검색, 빅데이터, AI, 마이크로서비스 및 개발자가 아름답고 빠르며 안정적이고 확장 가능한 애플리케이션을 만드는 데 도움이 되는 모든 것에 대해 글을 쓰는 것을 좋아합니다.

1개의 응답

  1. Agombia 아바타
    Agombia

    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.

댓글 남기기

카우치베이스 카펠라를 시작할 준비가 되셨나요?

개발 시작하기

NoSQL을 탐색하고, 리소스를 찾아보고, 튜토리얼을 시작하려면 개발자 포털을 확인하세요.

카펠라 프리 사용하기

단 몇 번의 클릭으로 카우치베이스(Couchbase)를 직접 체험해 보세요. Capella DBaaS는 시작하기 가장 쉽고 빠른 방법입니다.

연락해

Couchbase 제품군에 대해 더 알고 싶으신가요? 저희가 도와드리겠습니다.