This library provides utilities to generate, parse and validate JWTs (JSON Web Tokens) used to implement an authentication mechanism over a REST API.
This library is designed to be installed by making use of Conan package manager. So, you just need to add the following requirement into your Conan recipe:
def requirements(self):
self.requires("JWTUtils/1.0.0@systelab/stable")
Version number of this code snipped is set just as an example. Replace it for the desired package to retrieve.
As this package is not available on the conan-center, you will also need to configure a remote repository before installing dependencies:
conan remote add systelab-public https://csw.jfrog.io/artifactory/api/conan/cpp-conan-production-local
See Conan documentation for further details on how to integrate this package with your build system.
See BUILD.md document for details.
Use the systelab::jwt::TokenBuilderService
class to generate a valid token containing a vector of claims:
#include "RapidJSONAdapter/JSONAdapter.h"
#include "JWTUtils/Services/TokenBuilderService.h"
systelab::json::rapidjson::JSONAdapter jsonAdapter;
systelab::jwt::TokenBuilderService tokenBuilderService(jsonAdapter);
std::string secretKey = "Here goes your secret key";
std::vector< std::pair<std::string, std::string> > claims =
{ {"sub", "1234567890"}, {"name", "John Doe"}, {"iat", "1516239022"} };
std::string token = tokenBuilderService.buildJWT(secretKey, claims);
Use the systelab::jwt::TokenParserService
class to parse a JWT token and retrieve the claims contained on it. It will return false when the provided JWT is not valid.
#include "RapidJSONAdapter/JSONAdapter.h"
#include "JWTUtils/Services/TokenParserService.h"
systelab::json::rapidjson::JSONAdapter jsonAdapter;
systelab::jwt::TokenParserService tokenParserService(jsonAdapter);
std::string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoiMTUxNjIzOTAyMiJ9."
"5ODOvx-citIP2b7EbnG1TlSUcoAKmCeOyE-_Kw3-dLo";
std::string secretKey = "Here goes your secret key";
std::vector< std::pair<std::string, std::string> > claims;
bool valid = tokenParserService.validateJWT(token, secretKey, claims);