GitHub OAuth with Java
OAuth is commonly used as a way for web surfers to log into third party web sites using their Google, Facebook or Twitter accounts.
In the example Basics of Authentication for the GitHub OAuth they create a Ruby server to show the Web Application Flow for using OAuth with GitHub.
Basically the Web Flow consists of three parts:
- Your app redirects the user to GitHub to request access.
- GitHub redirects back to your site with a temporary code that can be exchanged for an access token.
- With the temporary code the access token to access the GitHub API can be requested.
The different GitHub Java-API’s all require the Access-Token. Accordingly we need to get the Access-Token first before we’re able to use those libraries.
In the following example we want to use Java, the Spark Web Framework, the Rest-client Unirest and the template engine freemarker to achieve the same functionality of the Ruby server in the Basics of Authentication Guide.
The following code can also be found on GitHub.
Create a basic server
First register a new OAuth application.
http://localhost:4567/callback as the Authorization callback URL. The Client ID and Client Secret should be stored as environment variables:
Create the template
FreeMarkerTemplateEngine class, that will render the template:
Create the route displaying the template. Provide the
client_id to the template.
Create the callback route and access the provided session code (
Use the session code to
With the access-token we’re ready to use the GitHub API. For example to get the username for an access-token:
But you should probably use a specialized library instead of accessing the API through REST.