How to create an OAuth2 Client in Golang

OAuth2 Tutorial

In this post, we will see how we can implement OAuth2 authentication in a Go web application.

We will create a working website allowing a user to sign in using GitHub authentication.

How OAuth2 Works

Let’s take a brief look at the OAuth protocol before we jump into implementation.

If you’ve ever seen a dialog like this, then you’ve probably used OAuth before:

gitlab using github oauth

Here, we are trying to log in to Gitlab using Github to authenticate.Advertisements

There are three parties in any OAuth mechanism:

  1. The client – The person, or user who is trying to log in
  2. The consumer – The application that the client wants to log into (which is Gitlab in this example)
  3. The service provider – The external application that authenticates the users identity. (which is Github in this example)

In this post, we’ll create a Go HTTP server (consumer) that uses Github’s OAuth2 API (service provider) to authenticate the user (client).

Let’s look at an overview of how this would work in practice.

oauth flow diagram

Let’s look at how to implement each part:Advertisements

Creating the Landing Page

Lets create the first part of the application, which is the landing page. This will be a basic HTML page, with a link that the user can click on to authenticate with Github.

We can create a new file, public/index.html:

<!DOCTYPE html>
      Login with github

The link URL has three key parts:

  • https// is the OAuth gateway for Github’s OAuth flow. All OAuth providers have a gateway URL you must send the user to proceed.
  • client_id=myclientid123 – this specifies the client ID of the application. This ID will tell Github about the identity of the consumer trying to use their OAuth service.OAuth service providers have portal in which you can register your consumer. On registration, you will receive a client ID (which we are using here as myclientid123), and a client secret (which we will use later on). The portal to register new applications for Github can be found on After
  • redirect_uri=http://localhost:8080/oauth/redirect – specifies the URL to redirect to with the request token, once the user has been authenticated by the service provider. Normally, you will have to set this value on the registration portal as well, to prevent anyone from setting malicious callback URLs.