DEV Community

Lane Wagner
Lane Wagner

Posted on • Originally published at qvault.io on

How To Build JWT’s in Go (Golang)

By Lane Wagner – @wagslane on Twitter

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 method for representing claims securely between two parties.

https://jwt.io/

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:

  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 and signs 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. Make sure you have the code cloned locally:

go get github.com/dgrijalva/jwt-go
Enter fullscreen mode Exit fullscreen mode

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:

type customClaims struct {
    Username string `json:"username"`
    jwt.StandardClaims
}
Enter fullscreen mode Exit fullscreen mode

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:

claims := customClaims{
    Username: username,
    StandardClaims: jwt.StandardClaims{
        ExpiresAt: 15000,
        Issuer: "nameOfWebsiteHere",
    },
}
Enter fullscreen mode Exit fullscreen mode

Create an unsigned token from the claims:

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
Enter fullscreen mode Exit fullscreen mode

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"))
Enter fullscreen mode Exit fullscreen mode

Now 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 is idiomatic to use the Authorization HTTP header:

Authorization: Bearer {jwt}
Enter fullscreen mode Exit fullscreen mode

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 
    },
)
Enter fullscreen mode Exit fullscreen mode

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")
}
Enter fullscreen mode Exit fullscreen mode

Check if the token is expired:

if claims.ExpiresAt < time.Now().UTC().Unix() {
    return errors.New("JWT is expired")
}
Enter fullscreen mode Exit fullscreen mode

You now know the username of the authenticated user!

username := claims.Username
Enter fullscreen mode Exit fullscreen mode

For full examples take a look at the package’s tests.

Thanks For Reading!

Lane on Twitter: @wagslane

Lane on Dev.to: wagslane

Download Qvault: https://qvault.io

The post How To Build JWT’s in Go (Golang) appeared first on Qvault.

Top comments (0)