JWT Authentication in Golang
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’ll 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 method for representing claims securely between two parties.
More simply put, JWT’s are encoded JSON 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:
- The user sends a username and password to the server
- The server verifies username and password are correct
- The server creates a JSON object (also known as the “claims”) that looks something like this:
{"username":"wagslane"}
- The server encodes and signs the JSON object, creating a JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IndhZ3NsYW5lIn0.ov6d8XtwQoKUwsYahk9UwH333NICElFSs6ag6pINyPQ
- The user’s web client saves the JWT for later use
- When the user makes a request to a protected endpoint, it passes the JWT along in an HTTP header
- The server checks the signature on the JWT to make sure the JWT was originally created by the same server
- The server reads the claims and gives permission to the request to operate as “wagslane”
Create a JWT
We’re going to use a popular library for dealing with JSON Web Tokens in Go, jwt-go. Make sure you have the code cloned locally:
go get https://github.com/golang-jwt/jwt
For simplicity, we’re going to use a symmetric encryption scheme. If you go this route, it just means that any server that can verify that a JWT is valid will also be allowed to issue new JWTs.
First, define a struct that will be used to represent claims to identify your users:
type customClaims struct {
Username string `json:"username"`
jwt.StandardClaims
}
The jwt.StandardClaims struct contains useful fields like expiry and issuer name. Now we’ll create some actual claims for the user that just logged in:
claims := customClaims{
Username: username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: 15000,
Issuer: "nameOfWebsiteHere",
},
}
Next let’s create an unsigned token from the claims:
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
Then we 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:
signedToken, err := token.SignedString([]byte("secureSecretText"))
Finally, the signed token can be sent back to the client.
Validating a JWT
When the client makes a request to a protected endpoint we can verify the JWT is authentic using the following steps.
*Note: It’s idiomatic to use the Authorization HTTP header:
Authorization: Bearer {jwt}
After receiving the JWT, validate the claims and verify the signature using the same private key:
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:
claims, ok := token.Claims.(*customClaims)
if !ok {
return errors.New("couldn't parse claims")
}
Check if the token is expired:
if claims.ExpiresAt < time.Now().UTC().Unix() {
return errors.New("jwt is expired")
}
You now know the username of the authenticated user!
username := claims.Username
For full examples take a look at the package’s tests. Let me know if I missed anything by hitting me up on Twitter!
Related Articles
BitBanged SPI in Go, An Explanation
Jan 09, 2020 by Lane Wagner - Boot.dev co-founder and backend engineer
I’m going to focus mostly on some design decisions and also how I went about writing an SPI interface using Go on a Raspberry Pi. I assume my readers have a basic understanding of what a Raspberry Pi is, and how basic electronics work. If not, read on anyway and I will be sure to include some valuable resources below.
Top 6 Golang Logging Best Practices
Jan 07, 2020 by Lane Wagner - Boot.dev co-founder and backend engineer
Let’s discuss a few rules of thumb for logging in Go, as well as some features you may not have heard of that can make debugging easier. Best practices for logging in Go are not so obvious and sometimes we need to look closer to see what is the best choice, considering the unique situation of error handling in Go.
How to Create Constant Maps, Slices, & Arrays in Golang
Oct 21, 2019 by Lane Wagner - Boot.dev co-founder and backend engineer
The quick answer is that Go does not support constant arrays, maps or slices. However, there are some great workarounds.
The Proper Use of Pointers in Go (Golang)
Sep 25, 2019 by Lane Wagner - Boot.dev co-founder and backend engineer
Go has become increasingly popular in recent years, especially in my local area. It has been consistently displacing other backend languages like Ruby, Python, C# and Java. Go is wanted for its simplicity, explicitness, speed, and low memory consumption.