Mirror of cpp-jwt
Find a file
2017-12-29 16:26:37 +05:30
examples Readme changes for example code and fixed header decoding 2017-12-29 16:26:37 +05:30
include/jwt Readme changes for example code and fixed header decoding 2017-12-29 16:26:37 +05:30
tests Readme changes for example code and fixed header decoding 2017-12-29 16:26:37 +05:30
cmake_command Cmake support added for tests. Complete.Huh. 2017-12-28 15:44:47 +05:30
CMakeLists.txt Readme changes for example code and fixed header decoding 2017-12-29 16:26:37 +05:30
LICENSE Create LICENSE 2017-12-27 15:31:51 +05:30
README.md Readme changes for example code and fixed header decoding 2017-12-29 16:26:37 +05:30

CPP-JWT

A C++14 library for JSON Web Tokens(JWT)

A little library built with lots of ❤︎ for working with JWT easier. By Arun Muralidharan.

Table of Contents

What is it ?

For the uninitiated, JSON Web Token(JWT) is a JSON based standard (RFC-7519) for creating assertions or access tokens that consists of some claims (encoded within the assertion). This assertion can be used in some kind of bearer authentication mechanism that the server will provide to clients, and the clients can make use of the provided assertion for accessing resources.

Few good resources on this material which I found useful are:

Example

Lets dive into see a simple example of encoding and decoding in Python. Taking the example of pyjwt module from its docs.

>>import jwt
>>key = 'secret'
>>
>>encoded = jwt.encode({'some': 'payload'}, key, algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg'
>>
>>decoded = jwt.decode(encoded, key, algorithms='HS256')
{'some': 'payload'}

Now, lets look at our C++ code doing the same thing.

#include <iostream>
#include "jwt/jwt.hpp"

int main() {
  using namespace jwt::params;

  auto key = "secret"; //Secret to use for the algorithm
  //Create JWT object
  jwt::jwt_object obj{algorithm("HS256"), payload({{"some", "payload"}}), secret(key)};

  //Get the encoded string/assertion
  auto enc_str = obj.signature();
  std::cout << enc_str << std::endl;

  //Decode
  auto dec_obj = jwt::decode(enc_str, algorithms({"hs256"}), secret(key));
  std::cout << dec_obj.header() << std::endl;
  std::cout << dec_obj.payload() << std::endl;

  return 0;
}

It outputs:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg
{"alg":"HS256","typ":"JWT"}
{"some":"payload"}

Almost the same API, except for some ugliness here and there. But close enough!