Site icon Golang Libraries, Apps, Golang Jobs and Go Tutorials

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:

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.

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>
<html>
  <body>
    <a
      href="https://github.com/login/oauth/authorize?client_id=myclientid123&redirect_uri=http://localhost:8080/oauth/redirect"
    >
      Login with github
    </a>
  </body>
</html>

The link URL has three key parts:

Exit mobile version