Private claims

Private claims are used to identify one token from another. They can be used for authorization. Authorization is a process of identifying which client made the request. Multi-tenancy refers to the situation of multiple clients accessing an API on a system. The server can set a private claim called username on the payload of the token. Next time, the server can read this payload back and get the username, and then use that username to authorize and customize the API response. It is similar to a cookie but in a different way.

For example, username: Indiana Jones is a private claim in the following payload:

{
"sub": "1234567890",
"username": "Indiana Jones",
"admin": true
}

Public claims are similar to private claims, but they should be registered with the IANA JWT Registry to make them as a standard. We limit the use of these.

A signature can be created by performing this operation (this is not code, just an illustration):

signature = HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)

This is simply performing an encryption algorithm on the Base64Url-encoded header and payload with a secret. This secret can be any string. It is exactly the same as the secret we used in the previous cookie session. This secret is usually saved in the environment variable and loaded into the program.

Now, we append the encoded header, encoded payload, and signature to get our token string, as follows:

tokenString = base64UrlEncode(header) + "." + base64UrlEncode(payload) + "." + signature

This is how a JWT token is generated. There are a few Go packages that can generate and verify a JWT. One such popular package is jwt-go. We are going to create a project in the next section that uses jwt-go to sign a JWT and also verify it. We can install this package using the following dep command:

dep ensure -add github.com/dgrijalva/jwt-go 

This is the official GitHub page for the project: https://github.com/dgrijalva/jwt-go

The package provides a few functions that allow us to create tokens. There are many other packages with different additional features. You can see all the available packages and features that are supported at https://jwt.io/#libraries-io.