| 1 |
#include <chrono> |
| 2 |
#include <cassert> |
| 3 |
#include <fstream> |
| 4 |
#include <string> |
| 5 |
#include <iostream> |
| 6 |
#include "jwt/jwt.hpp" |
| 7 |
|
| 8 |
/*** |
| 9 |
* STEPS TO GENERATE RSA PRIVATE PUBLIC KEYPAIR. |
| 10 |
* |
| 11 |
* 1. openssl genrsa -out jwtRS256.key 1024 |
| 12 |
* 2. openssl rsa -in jwtRS256.key -pubout -outform PEM -out jwtRS256.key.pub |
| 13 |
*/ |
| 14 |
|
| 15 |
std::string read_from_file(const std::string& path) |
| 16 |
{ |
| 17 |
std::string contents; |
| 18 |
std::ifstream is{path, std::ifstream::binary}; |
| 19 |
|
| 20 |
if (is) { |
| 21 |
// get length of file: |
| 22 |
is.seekg (0, is.end); |
| 23 |
auto length = is.tellg(); |
| 24 |
is.seekg (0, is.beg); |
| 25 |
contents.resize(length); |
| 26 |
|
| 27 |
is.read(&contents[0], length); |
| 28 |
if (!is) { |
| 29 |
is.close(); |
| 30 |
return {}; |
| 31 |
} |
| 32 |
} else { |
| 33 |
std::cerr << "FILE not FOUND!!" << std::endl; |
| 34 |
} |
| 35 |
|
| 36 |
is.close(); |
| 37 |
return contents; |
| 38 |
} |
| 39 |
|
| 40 |
int main() { |
| 41 |
using namespace jwt::params; |
| 42 |
const std::string priv_key_path = std::string{CERT_ROOT_DIR} + "/jwtRS256.key"; |
| 43 |
const std::string pub_key_path = std::string{CERT_ROOT_DIR} + "/jwtRS256.key.pub"; |
| 44 |
|
| 45 |
auto priv_key = read_from_file(priv_key_path); |
| 46 |
|
| 47 |
jwt::jwt_object obj{algorithm("RS256"), secret(priv_key), payload({{"user", "admin"}})}; |
| 48 |
|
| 49 |
//Use add_claim API to add claim values which are |
| 50 |
// _not_ strings. |
| 51 |
// For eg: `iat` and `exp` claims below. |
| 52 |
// Other claims could have been added in the payload |
| 53 |
// function above as they are just stringy things. |
| 54 |
obj.add_claim("iss", "arun.muralidharan") |
| 55 |
.add_claim("sub", "test") |
| 56 |
.add_claim("id", "a-b-c-d-e-f-1-2-3") |
| 57 |
.add_claim("iat", 1513862371) |
| 58 |
.add_claim("exp", std::chrono::system_clock::now() + std::chrono::seconds{10}) |
| 59 |
; |
| 60 |
|
| 61 |
//Use `has_claim` to check if the claim exists or not |
| 62 |
assert (obj.has_claim("iss")); |
| 63 |
assert (obj.has_claim("exp")); |
| 64 |
|
| 65 |
//Use `has_claim_with_value` to check if the claim exists |
| 66 |
//with a specific value or not. |
| 67 |
assert (obj.payload().has_claim_with_value("id", "a-b-c-d-e-f-1-2-3")); |
| 68 |
assert (obj.payload().has_claim_with_value("iat", 1513862371)); |
| 69 |
|
| 70 |
auto pub_key = read_from_file(pub_key_path); |
| 71 |
|
| 72 |
std::error_code ec{}; |
| 73 |
auto sign = obj.signature(ec); |
| 74 |
if (ec) { |
| 75 |
std::cerr << ec.message() << std::endl; |
| 76 |
return 1; |
| 77 |
} |
| 78 |
|
| 79 |
auto dec_obj = jwt::decode(sign, algorithms({"RS256"}), verify(false), secret(pub_key)); |
| 80 |
|
| 81 |
return 0; |
| 82 |
} |