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:
There are three parties in any OAuth mechanism:
- The client – The person, or user who is trying to log in
- The consumer – The application that the client wants to log into (which is Gitlab in this example)
- 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,
<!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:
https//github.com/login/oauth/authorizeis 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 https://github.com/settings/applications/new. 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.