Recently I started working with JWT based authentication. After user login, a user token is generated which will look like
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ".
It consist of three parts each separated with a dot(.).First part is header which Base64 encoded. After decoding we will get something like
{
"alg": "HS256", //Algorithm used
"typ": "JWT"
}
Second part is claims and Base64 encoded. After decoding we will get something like
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
Third part is signature and is generated with
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret base64 encoded
)
Now what is this secret key and how to generate this secret key??
I tried some online generator like "http://kjur.github.io/jsjws/tool_jwt.html"
but dint get much help.
The algorithm (HS256
) used to sign the JWT means that the secret is a symmetric key that is known by both the sender and the receiver. It is negotiated and distributed out of band. Hence, if you're the intended recipient of the token, the sender should have provided you with the secret out of band.
If you're the sender, you can use an arbitrary string of bytes as the secret, it can be generated or purposely chosen. You have to make sure that you provide the secret to the intended recipient out of band.
For the record, the 3 elements in the JWT are not base64-encoded but base64url-encoded, which is a variant of base64 encoding that results in a URL-safe value.
You can write your own generator. The secret key is essentially a byte array. Make sure that the string that you convert to a byte array is base64 encoded.
In Java you could do something like this.
String key = "random_secret_key";
String base64Key = DatatypeConverter.printBase64Binary(key.getBytes());
byte[] secretBytes = DatatypeConverter.parseBase64Binary(base64Key);
What is the secret key
The secret key is combined with the header and the payload to create a unique hash. You are only able to verify this hash if you have the secret key.
How to generate the key
You can choose a good, long password. Or you can generate it from a site like this.
Example (but don't use this one now):
8Zz5tw0Ionm3XPZZfN0NOml3z9FMfmpgXwovR9fp6ryDIoGRM8EPHAB6iHsc0fb