Tuesday, January 24, 2017

Making a Custom Signed Access Token

// The Access Token
In an earlier post, I talked about access token and how they're built. They're comprised of a payload and then a hash of the payload and some secret which makes it a signed token.  A popular implementation of this approach is the JWT, but we'll cover that another time and we'll just make our own simple access token. Lets call it the DSBAccessToken. Sounds official right?

// DSBAccessToken
The DSBAccessToken is our own simple access token that is signed and contains a payload of just a string. The structure of it, might look like the figure below. On the left is the message, the plus sign indicates our delimiter which separates the message and signature, and finally the signature.

A very simple token consisting of a string payload and a hash of the message and a secret

For our case, the message is just a string, but a lot more information can be stored in there. You can place pretty much anything in there that is serializable or binary data. This includes JSON, which is very convenient and the basis of the JWT. JWTs for example, are very structured and contain several parts to the payload. We'll see some steps here in order to make a token.

// Steps to Making a Signed Access Token
The steps to creating a signed access token are pretty straight forward and simple. Below is a simple graphic showing the flow.

  1. Pass the secret and payload through SHA256
  2. Base64 encode the message and the signature
  3. Concatenate the Base64 version of the payload and the signature with a delimiter, usually a '.'

Very basic flow of creating a signed token

// Verifying the token
Verifying the token is pretty simple as well. Since we should know the secret, we just need to make sure the payload of the token we received produces the same signature with our secret. The flow for this process is pretty much like creating the token but in reverse and the last step is to compare the signature we create with the signature of the access token we received.

  1. Split the access token on the delimiter. For us its the '.'
  2. Base64 decode the message and the signature.
  3. Pass the message we received and our secret through SHA256
  4. Compare the signature we just made with the one we received.
  5. If the signatures are the same, then the access token was untampered with. If the signatures are different, then the data changed or tampered with.


// NOTE:
I've been using base64 and base64url interchangeably. If you plan on passing your token along in the query parameters, then base64url needs to be used. If the token is being sent by some other means, either way is fine, just use the correct decoding on the other end.   

No comments:

Post a Comment