Debian Codegraph @

examples/simple_ex2.cc

raw
1 #include <chrono>
2 #include <cassert>
3 #include <iostream>
4 #include "jwt/jwt.hpp"
5
6 int main() {
7 using namespace jwt::params;
8
9 jwt::jwt_object obj{algorithm("HS256"), secret("secret"), payload({{"user", "admin"}})};
10
11 //Use add_claim API to add claim values which are
12 // _not_ strings.
13 // For eg: `iat` and `exp` claims below.
14 // Other claims could have been added in the payload
15 // function above as they are just stringy things.
16 obj.add_claim("iss", "arun.muralidharan")
17 .add_claim("sub", "test")
18 .add_claim("id", "a-b-c-d-e-f-1-2-3")
19 .add_claim("iat", 1513862371)
20 .add_claim("exp", std::chrono::system_clock::now() + std::chrono::seconds{10})
21 ;
22
23 //Use `has_claim` to check if the claim exists or not
24 assert (obj.has_claim("iss"));
25 assert (obj.has_claim("exp"));
26
27 //Use `has_claim_with_value` to check if the claim exists
28 //with a specific value or not.
29 assert (obj.payload().has_claim_with_value("id", "a-b-c-d-e-f-1-2-3"));
30 assert (obj.payload().has_claim_with_value("iat", 1513862371));
31
32 //Remove a claim using `remove_claim` API.
33 //Most APIs have an overload which takes enum class type as well
34 //It can be used interchangeably with strings.
35 obj.remove_claim(jwt::registered_claims::expiration);
36 assert (!obj.has_claim("exp"));
37
38 //Using `add_claim` with extra features.
39 //Check return status and overwrite
40 assert (!obj.payload().add_claim("sub", "new test", false/*overwrite*/));
41
42 // Overwrite an existing claim
43 assert (obj.payload().add_claim("sub", "new test", true/*overwrite*/));
44
45 assert (obj.payload().has_claim_with_value("sub", "new test"));
46
47 return 0;
48 }