Categories
security tech

How To Build JWT’s in Go

Go is changing into highly regarded for backend internet building, and JWT’s are one of the most well liked techniques to care for authentication on API requests. In this newsletter, we’re going to move over the fundamentals of JWT’s and how one can put into effect a protected authentication technique in Go!

What is a JWT?

JSON Web Tokens are an open, business same old RFC 7519 manner for representing claims securely between two events.
More merely put, JWT’s are encoded JSON items which have been signed through the server, verifying authenticity.

For instance, when a person logs in to a web page secured by means of JWTs, the waft must glance one thing like this:

  1. The person sends a username and password to the server
  2. The server verifies username and password are proper
  3. The server creates a JSON object (aka claims) that appears like this:
    {"username":"wagslane"}
    
    
  4. The server encodes and indicators the JSON object, making a JWT:
    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IndhZ3NsYW5lIn0.ov6d8XtwQoKUwsYahk9UwH333NICElFSs6ag6pINyPQ
    
  5. The person’s internet consumer saves the JWT for later use
  6. When the person makes a request to a safe endpoint, it passes the JWT is alongside in an HTTP header
  7. The server assessments the signature at the JWT to ensure the JWT was once initially created through the similar server
  8. The server reads the claims and provides permission to the request to perform as ”
    wagslane
    

Create a JWT

We are going to make use of a well-liked library for coping with JSON Web Tokens’s in Go, jwt-go. Make certain you could have the code cloned in the neighborhood:
move get github.com/dgrijalva/jwt-go

For simplicity, we’re construction a symmetric encryption scheme. This way we think that the server that creates the JWTs can also be the one server that will likely be verifying them.

First, outline a struct that will likely be used to constitute claims to spot our customers:

kind customizedClaims struct { Username string `json:"username"` jwt.Same oldClaims
}

The jwt.Same oldClaims struct incorporates helpful fields like expiry and issuer title. Now we can create some exact claims for the person that simply logged in:

claims := customizedClaims{
 Username: username,
 Same oldClaims: jwt.Same oldClaims{
 ExpiresAt: 15000,
 Issuer: "nameOfWebsiteHere", },
}

Create an unsigned token from the claims:

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

Sign the token the use of a protected non-public key. In manufacturing remember to use an actual non-public key, ideally a minimum of 256 bits in period:

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

Now the signed token can also be despatched again to the buyer.

Validating a JWT

When the buyer makes a request to a safe endpoint we will be able to examine the JWT is original the use of the next steps.

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

Authorization: Bearer {jwt}

After receiving the JWT, validate the claims and examine the signature the use of the similar non-public key:

token, err := jwt.ParseWithClaims( jwtFromHeader, &customizedClaims{}, func(token *jwt.Token) (interface{}, error) { go back []byte("secureSecretText"), nil },
)

If the claims were tampered with then the err variable may not be nil.

Parse the claims from the token:

claims, adequate := token.Claims.(*customizedClaims)
if !adequate { go back mistakes.New("Couldn't parse claims")
}

Check if the token is expired:

if claims.ExpiresAt < time.Now().UTC().Unix() { go back mistakes.New("JWT is expired")
}

You now know the username of the authenticated person!

username := claims.Username
For complete examples check out the package deal’s assessments.

Thanks For Reading!

By Lane Wagner

Previously printed at https://qvault.io/2020/02/20/how-to-build-jwts-in-go-golang/