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.

13 thoughts on “Spring Boot and OAuth2 with JDBC”

  1. I send a POST request through POSTMAN. My request is as below:

    http://localhost:8181/OauthExampleApplication/oauth/token?grant_type=password&username=dazito&password=dazito

    basic authetication for user in the account is username = web, password = secret

    but i got the following error.

    “error”: “unauthorized”,
    “error_description”: “Full authentication is required to access this resource”

    i can’t get the access token. How can i get relief from this error and get the access token ?

  2. Hi, I tested tour solution but I have some problem. What’s exact requests sequence to obtain a token and use it? POST to /oauth/token ? A

    1. Hello,

      Here is a sample request:
      *******
      POST http://localhost:8081/oauth/token HTTP/1.1
      Accept-Encoding: gzip,deflate
      Content-Type: application/x-www-form-urlencoded
      Content-Length: 90
      Host: localhost:8081
      Connection: Keep-Alive
      User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

      client_secret=secret&client_id=web&grant_type=password&username=dazito&password=dazito.com
      *****
      FYI, I’ve updated the method public void configure(AuthorizationServerSecurityConfigurer security) in order to allow post authorization (i.e. don’t need Basic Authentication)

      @Override
      public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
      security.allowFormAuthenticationForClients().checkTokenAccess(“permitAll()”);
      }

      1. Great! Work fine. But I dont understand beacause work only in x-www-form-urlencoded. If I use POSTMAN I can’t use RAW application/json option. Also for retriving data from controller http://localhost:8080/account…. If I send body x-www-form-urlencoded WORK! If I send body raw application/json DON’T WORK!!!

  3. I am getting error like bad credential
    localhost:9000/oauth/token?client_secret=secret&client_id=web&grant_type=client_credentials&username=chandu&password=chandu123
    username and password already exist my account table

    error:

    {
    “timestamp”: 1512399664149,
    “status”: 401,
    “error”: “Unauthorized”,
    “message”: “Bad credentials”,
    “path”: “/oauth/token”
    }
    can you please give me proper way to call oauth2.0 server

  4. curl -v -X POST -H “Authorization: Bearer X1X2X3X4X5X6X7X8X9X” http://localhost:8081/account

    gives me following output:

    * Connection #0 to host localhost left intact
    {“error”:”invalid_token”,”error_description”:”Invalid access token: X1X2X3X4X5X6X7X8X9X”}

    1. $ curl -i -X POST -H “Authorization:Bearer 841e8505-756a-4b65-8bd7-0285d2636bd3” “http://localhost:8081/account”

  5. Hi, the access tokens and refresh tokens are stored in encrypted form, so how to get an access token decrypted and then use it to call an API?

Leave a Reply

Your email address will not be published. Required fields are marked *

Enter Captcha Here : *

Reload Image