Search code examples
springspring-oauth2

Using JdbcTokenStore for JWT


for my REST API I am using JWT's for OAuth2 authorization. Currently I am extending JwtTokenStore to store the refresh tokens in memory so that I am able to revoke them.

// TODO: This is a temporary in memory solution that needs to be replaced with a concrete persistent implementation.
public class MyJwtTokenStore extends JwtTokenStore {

    private List<OAuth2RefreshToken> refreshTokens;

    public MyJwtTokenStore(JwtAccessTokenConverter jwtTokenEnhancer) {
        super(jwtTokenEnhancer);
        refreshTokens = new ArrayList<>();
    }

    @Override
    public OAuth2RefreshToken readRefreshToken(String tokenValue) {
        OAuth2RefreshToken refreshToken = super.readRefreshToken(tokenValue);
        if (!refreshTokens.contains(refreshToken)) {
            throw new InvalidGrantException("Invalid refresh token: " + tokenValue);
        }
        return refreshToken;
    }

    @Override
    public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
        refreshTokens.add(refreshToken);
    }

    @Override
    public void removeRefreshToken(OAuth2RefreshToken token) {
        refreshTokens.remove(token);
    }
}

I would like start storing these refresh tokens in a database rather than in memory. Spring provides us with JdbcTokenStore, but if I extend that class then I am unable to set a JwtAccessTokenConverter in the constructor. I know that I could just implement my own method of saving/retrieving the JWTs but I would like to take advantage of the out of the box support for the schema at https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/test/resources/schema.sql which the JdbcTokenStore provides.

create table oauth_refresh_token (
  token_id VARCHAR(256),
  token LONGVARBINARY,
  authentication LONGVARBINARY
); 

Does Spring support storing JWT in a data source? I need something like a "JwtJdbcTokenStore". What is a good way to go about doing this but still use the predefined queries and operations from JdbcTokenStore?


Solution

  • No, Spring doesn't supports this. Refer to this thread https://github.com/spring-projects/spring-security-oauth/issues/687

    Persisting JWT tokens is irrelevant since JWT tokens are self contained, everything you need to know is already available in that token.

    Having said that, if you have requirement for persisting them, then you will have to write custom logic for the same.