How To Build JWT’s in Go (Golang)
Tags: cryptography, education, go, programming
Published: 2020-02-20 13:56:37

---
title: How To Build JWT’s in Go (Golang)
published: true
date: 2020-02-20 13:55:43 UTC
tags: cryptography,education,golang,programming
canonical_url: https://qvault.io/2020/02/20/how-to-build-jwts-in-go-golang/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-build-jwts-in-go-golang
---

By Lane Wagner – [@wagslane](https://twitter.com/wagslane) on Twitter

![](https://qvault.io/wp-content/uploads/2020/02/logo-400.png)

Go is becoming very popular for backend web development, and JWT’s are one of the most popular ways to handle authentication on API requests. In this article, we are going to go over the basics of JWT’s and how to implement a secure authentication strategy in Go!

## What is a JWT?

> JSON Web Tokens are an open, industry standard [RFC 7519](https://tools.ietf.org/html/rfc7519) method for representing claims securely between two parties.
> 
> <cite><a href="https://jwt.io/">https://jwt.io/</a></cite>

More simply put, JWT’s are encoded [JSON](https://www.w3schools.com/js/js_json_objects.asp) objects that have been signed by the server, verifying authenticity.

For example, when a user logs in to a website secured via JWTs, the flow should look something like this:

1. The user sends a username and password to the server
2. The server verifies username and password are correct
3. The server creates a JSON object (aka claims) that looks like this:
  1. _{“username”:”wagslane”}_
4. The server [encodes](https://qvault.io/2019/08/14/stop-with-the-obfuscation-encoding-and-encryption-are-not-the-same/) and [signs](https://qvault.io/2019/12/12/hmac-and-mac-explained-simply-building-secure-auth-with-jwts/) the JSON object, creating a JWT:
  1. _eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IndhZ3NsYW5lIn0.ov6d8XtwQoKUwsYahk9UwH333NICElFSs6ag6pINyPQ_
5. The user’s web client saves the JWT for later use
6. When the user makes a request to a protected endpoint, the JWT is passed along in an HTTP header
7. The server checks the signature on the JWT to make sure the JWT was originally created by the same server
8. The server reads the claims and gives permission to the request to operate as “wagslane”

## Create a JWT

We are going to use a popular library for dealing with JSON Web Tokens’s in Go, [jwt-go](https://github.com/dgrijalva/jwt-go). Make sure you have the code cloned locally:

```bash
go get github.com/dgrijalva/jwt-go
```

For simplicity, we are building a symmetric encryption scheme. This means we assume that the server that creates the JWTs will also be the only server that will be verifying them.

First, define a struct that will be used to represent claims to identify our users:

```golang
type customClaims struct {
	Username string `json:"username"`
	jwt.StandardClaims
}
```

The _jwt.StandardClaims_ struct contains useful fields like _expiry_ and _issuer name_. Now we will create some actual claims for the user that just logged in:

```golang
claims := customClaims{
	Username: username,
	StandardClaims: jwt.StandardClaims{
		ExpiresAt: 15000,
		Issuer: "nameOfWebsiteHere",
	},
}
```

Create an unsigned token from the claims:

```golang
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
```

Sign the token using a secure private key. In production make sure you use a real private key, preferably at least 256 bits in length:

```golang
signedToken, err := token.SignedString([]byte("secureSecretText"))
```

Now the signed token can be sent back to the client.

## Validating a JWT

![](https://qvault.io/wp-content/uploads/2020/02/71KUQgscjDL._AC_SX466_.jpg)

When the client makes a request to a protected endpoint we can verify the JWT is authentic using the following steps.

\*Note: It is idiomatic to use the Authorization HTTP header:

```json
Authorization: Bearer {jwt}
```

After receiving the JWT, validate the claims and verify the signature using the same private key:

```golang
token, err := jwt.ParseWithClaims(
	jwtFromHeader,
	&customClaims{},
	func(token *jwt.Token) (interface{}, error) {
		return []byte("secureSecretText"), nil 
	},
)
```

If the claims have been tampered with then the err variable will not be **nil**.

Parse the claims from the token:

```golang
claims, ok := token.Claims.(*customClaims)
if !ok {
	return errors.New("Couldn't parse claims")
}
```

Check if the token is expired:

```golang
if claims.ExpiresAt < time.Now().UTC().Unix() {
	return errors.New("JWT is expired")
}
```

You now know the username of the authenticated user!

```golang
username := claims.Username
```

For full examples take a look at the package’s [tests](https://github.com/dgrijalva/jwt-go/blob/master/example_test.go).

## Thanks For Reading!

Lane on Twitter: [@wagslane](https://twitter.com/wagslane)

Lane on Dev.to: [wagslane](https://dev.to/wagslane)

Download Qvault: [https://qvault.io](https://qvault.io/)

The post [How To Build JWT’s in Go (Golang)](https://qvault.io/2020/02/20/how-to-build-jwts-in-go-golang/) appeared first on [Qvault](https://qvault.io).