Code Monkey home page Code Monkey logo

jwt-cpp's Introduction

Hi there, I'm Dominik Thalhammer πŸ‘‹

  • πŸ”­ I'm currently working on a personal project!
  • 🌱 I'm currently learning UI/UX Design for the web and desktop apps
  • πŸ‘― I'm looking to collaborate with other developers
  • πŸ₯… 2022 Goals: Give impact to society
  • βš™οΈ I am a Full-Stack developer with focus on High Performance Microservice Backends

Connect with me:

thalhammer.it Dominik Thalhammer | LinkedIn Thalhammer | Github Thalhammer | Gitlab Thalhammer | Matrix


Languages and Tools:

C++ C C# Lua RPG Typescript Javascript Html 5 CSS 3 gRPC Linux Docker MySQL Git



Thalhammer's Github Stats

Thalhammer's Github Stats

jwt-cpp's People

Contributors

aboseley avatar adesitter avatar akyidrian avatar arjen-hoogesteger avatar bugdea1er avatar criadoperez avatar csegarragonz avatar dennisyakovlev avatar diogo-strube avatar erwanlegrand avatar faustocarva avatar galuha avatar garethsb avatar janblome avatar jbajwa avatar jonasborchelt avatar justend29 avatar ka0o0 avatar kleinmrk avatar martin-flaska avatar matze avatar optiligence avatar pliablepixels avatar prince-chrismc avatar prosperoh avatar richardhozak avatar sdmg15 avatar sjanel avatar sp3eder avatar thalhammer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jwt-cpp's Issues

Error building project

I have included this library into my project via CMake like this

  1. include_directories(../common/modules/jwt-cpp-0.3.1/include) # Json Web Token (library)
  2. In header file
#include <jwt-cpp/jwt.h>  // jwt
#include <iostream>

I tried to build the project using the example code

auto token = jwt::create()
	.set_issuer("auth0")
	.set_type("JWS")
	.set_payload_claim("sample", jwt::claim(std::string("test")))
	.sign(jwt::algorithm::hs256{"secret"});

As well not having any code at all in my encryption method

std::string DataProtector::encrypt(const std::string& input)
{
    auto key = "secret"; //Secret to use for the algorithm
  //Create JWT object

    //Get the encoded string/assertion
    return "";
}

In both cases, i get this.

Severity	Code	Description	Project	File	Line	Suppression State
Error	C2665	'std::unique_ptr<BIO,void (__cdecl *)(BIO *)>::unique_ptr': none of the 2 overloads could convert all the argument types	work	C:\Users\work\Documents\workspace\SDK\common\modules\jwt-cpp-0.3.1\include\jwt-cpp\jwt.h	81

My setup:
OS: Windows 10
IDE: Visual Studio Community 2019 version Version 16.4.5

What should i do to make this work?

Mac compile error - undefined symbols

while compiling on mac, comes error
Undefined symbols for architecture x86_64:
"_EVP_sha256", referenced from:
jwt::algorithm::hs256::hs256(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator >) in main.cpp.o
"_HMAC", referenced from:
jwt::algorithm::hmacsha::sign(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator > const&) const in main.cpp.o
ld: symbol(s) not found for architecture x86_64

Exp verification fails for dates in the far future

Tokens with expiration dates in the far future (roughly beyond year 2250) are not calculated properly on Debian. I believe this is actually either a problem (or limitation) of using std::chrono::system_clock when getting exp as a date.

I have a JWT with an exp date as: 15393024000 that we use for testing purposes and it fails validation. The resulting local time of that exp in the verifier is 03/25/1873 19:29:25. Below is the code I was using to print that from within the verifier:

auto exp_tt = std::chrono::system_clock::to_time_t(exp);
std::tm * ptm = std::localtime(&exp_tt);
char buffer[32] = {0};
std::strftime(buffer, 32, "%m/%d/%Y %H:%M:%S", ptm);
printf("Exp: %s\n", buffer);

I did not try every permutation of dates but the latest I tried that seemed to work was this: 8860621278 which corresponds to 10/13/2250 11:41:18

Any guidance on this would be much appreciated, I was unable to find any documentation on limitations of the system_clock and this issue did not seem to arise on Windows or Mac OS.

Buggy ECDSA implementation

This vaguely relates to #49.

There's an issue with the ECDSA implementation, that took me some time to debug. Unfortunately, due to the nature of my contract, I can't submit a fix. But I can provide an explanation.

The TL;DR is, that for SHA-256, you need a key from the P-256 curve, for SHA-384 from the P-384 curve, and for SHA-512 from the P-521 curve. The current implementation allows using SHA-512 with a P-256 curve key, which leads to signatures that may not be verifiable by other implementations.

Now... there are concerns with using NIST's curves. But you can get EC groups with the same output lengths from different groups, so what I'd base this on is the EC_GROUP_order_bits() function - that has to be larger or equal to the SHA output bits (or you match them exactly as I described above, as you wish).

When you use matching sizes, you'll see that the zero-padding you do in the sign() method doesn't produce endless AAAAAA... prefixes, but will typically pad no more than a byte.

For reading up, I'll refer you to RFC7519 Section 8, which refers to encryption algorithms, particularly the ECDSA usage, from RFC7518 Section 3.4, which in turn lists the permissible curve + SHA combinations. It also lists that the curves to be used are from NIST's FIPS PUB 186-4 aka the Digital Signature Standard.

Hope that helps!

Thread Safety

Once done you can use it to verify any number of tokens. Since verifing does not modify the verifier you can reuse it as often as you like.

Does it mean that verify method is thread-safe?

failed to load private key: PEM_read_bio_RSAPrivateKey failed

Hi,

After preparing this JWT library, and added this project into a library dependancie on my project;
I got a problem, i finish on the try catch exception who say: failed to load private key: "PEM_read_bio_RSAPrivateKey failed"; that means than the privateKey i passed in parameter is wrong.
But here's how look my public and private key:

The content of both of my variables:
Public :
-----BEGIN PUBLIC KEY-----
blablabla my public key
-----END PUBLIC KEY-----

PrivateKey :
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,6C4D9FDD65EB0A2DC645794FEA85E872

blabla my private key
-----END RSA PRIVATE KEY-----

And how i instantiate and call my verifier:
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::rs256{ publicKey, privateKey });
//.with_issuer("auth0"); I commented it, btw i don't understand at 100% what issuer is for, i don't need it normally.. ?

verifier.verify(decoded_token); 

Btw my decoded_token is my token without the Bearer.
@Thalhammer

I wanted to know too, if we have to automatically give the privateKey if we already give the public key

Libcypto issue when integrated with x64 library

When deploying a dll built on x64 using the JWT library that refers libcrypto, the dll fails to load. Please confirm the version of libcryto being used by the JWT library or do we have to make any changes for integrating with x64 dll.

Signature Verification failing at EVP_Verify_Final

!EVP_VerifyFinal(ctx.get(), (const unsigned char*)signature.data(), signature.size(), pkey.get()) results in exception.
I am verifying RS256 JWT and generating the public key through certificate.
In debug mode i have verified public key generated successfully through certificate
Checked the signature verification on JWT.IO with the same generated public key

claim() compile error

After I've upgraded I have compilation errors :(

token->token = jwt::create()
    .set_type("JWS")
    .set_payload_claim("sample", jwt::claim(std::string("TEST")))
    .set_payload_claim("name", jwt::claim(std::string("Admin Name")))
    .set_issued_at(std::chrono::system_clock::now())
   .set_expires_at(std::chrono::system_clock::now() + std::chrono::seconds{JWT_TOKEN_TTL})
                        .sign(jwt::algorithm::hs512{JWT_SECRET}).c_str();;

And building

[ 97%] Building CXX object CMakeFiles/sandbox-lib.dirsrc/controller/authController.cpp.o
<command-line>: error: expected unqualified-id before numeric constant
/home/marcin/CLionProjects/cppapi/external/jwt-cpp/include/jwt-cpp/jwt.h:775:3: note: in expansion of macro β€˜JWT_CLAIM_EXPLICIT’
  775 |   JWT_CLAIM_EXPLICIT claim(std::string s)
      |   ^~~~~~~~~~~~~~~~~~
<command-line>: error: expected unqualified-id before numeric constant
/home/marcin/CLionProjects/cppapi/external/jwt-cpp/include/jwt-cpp/jwt.h:778:3: note: in expansion of macro β€˜JWT_CLAIM_EXPLICIT’
  778 |   JWT_CLAIM_EXPLICIT claim(const date& s)
      |   ^~~~~~~~~~~~~~~~~~
<command-line>: error: expected unqualified-id before numeric constant
/home/marcin/CLionProjects/cppapi/external/jwt-cpp/include/jwt-cpp/jwt.h:781:3: note: in expansion of macro β€˜JWT_CLAIM_EXPLICIT’
  781 |   JWT_CLAIM_EXPLICIT claim(const std::set<std::string>& s)
      |   ^~~~~~~~~~~~~~~~~~
<command-line>: error: expected unqualified-id before numeric constant
/home/marcin/CLionProjects/cppapi/external/jwt-cpp/include/jwt-cpp/jwt.h:784:3: note: in expansion of macro β€˜JWT_CLAIM_EXPLICIT’
  784 |   JWT_CLAIM_EXPLICIT claim(const picojson::value& val)
      |   ^~~~~~~~~~~~~~~~~~

std::bad_castinvalid token supplied

I just add bellow two lines then the token verify will failed:

	.set_issued_at(jwt::date(std::chrono::system_clock::now()))
	.set_expires_at(jwt::date(std::chrono::system_clock::now() + std::chrono::minutes{ 60 }))

Do I need special code for jwt::verify() to handle token expire?

Provide an error_code based interface

Currently jwt-cpp uses exceptions to signal errors and bad tokens.
In some environments exceptions might not be wanted (performance critical code) or not available (embedded).
In order to support this we need to convert all internal functions to use error codes.

Following the standard, an error_category should be unique in a given process. This is pretty much impossible for a header only library, but we should at least provide the option to have it compliant. One option would be to provide some preprocessor defines, which (when defined) will use extern to get the error category and a second one to emit the implementation in a translation unit. It then would be the users responsibility to make sure the actuall implementation resides in the main process and all other code has the extern option defined.

Checking roles

Hi,

I would like to know, how you can check the roles taken in the payload, roles is an attribut who look like this : ["myRole1", "myRole2"]...
Maybe there already a method ready like for with_issuer().

Thanks for your help, i think it can help many people.

comparison always false (-Wtype-limits)

Hi !
Just in case you missed it, compiling with gcc with -Wtype-limits produces the following warning:

jwt-cpp/jwt.h: In static member function β€˜static std::unique_ptr<bignum_st, void (*)(bignum_st*)> jwt::algorithm::ecdsa::raw2bn(const string&)’:
jwt-cpp/jwt.h:269:15: warning: comparison is always false due to limited range of data type [-Wtype-limits]
     if(raw[0] >= 0x80) {

I don't know if it's relevant in the way computations are done, but maybe you could be interested :)

picojson.h compile error

d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(895): warning C4003: not enough actual parameters for macro 'min'
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(895): warning C4003: not enough actual parameters for macro 'max'
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(895): error C2589: '(': illegal token on right side of '::'
1> d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(1066): note: see reference to function template instantiation 'bool picojson::_parse<Context,Iter>(Context &,picojson::input &)' being compiled
1> with
1> [
1> Context=picojson::default_parse_context,
1> Iter=std::_String_const_iterator<std::_String_val<std::_Simple_types>>
1> ]
1> d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(1084): note: see reference to function template instantiation 'Iter picojson::_parsepicojson::default_parse_context,Iter(Context &,const Iter &,const Iter &,std::string *)' being compiled
1> with
1> [
1> Iter=std::_String_const_iterator<std::_String_val<std::_Simple_types>>,
1> Context=picojson::default_parse_context
1> ]
1> d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(1089): note: see reference to function template instantiation 'Iter picojson::parse<std::_String_const_iterator<std::_String_val<std::_Simple_types>>>(picojson::value &,const Iter &,const Iter &,std::string *)' being compiled
1> with
1> [
1> Iter=std::_String_const_iterator<std::_String_val<std::_Simple_types>>
1> ]
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(895): error C2059: syntax error: '::'
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(896): error C2143: syntax error: missing ';' before '{'
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(902): error C2065: 'f': undeclared identifier
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(902): error C2065: 'num_str': undeclared identifier
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(902): error C2228: left of '.c_str' must have class/struct/union
1> d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(902): note: type is 'unknown-type'
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(902): error C2065: 'endp': undeclared identifier
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(903): error C2065: 'endp': undeclared identifier
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(903): error C2065: 'num_str': undeclared identifier
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(903): error C2228: left of '.c_str' must have class/struct/union
1> d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(903): note: type is 'unknown-type'
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(903): error C2228: left of '.size' must have class/struct/union
1> d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(903): note: type is 'unknown-type'
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(904): error C2065: 'f': undeclared identifier
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(909): error C2043: illegal break
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(911): error C3927: '->': trailing return type is not allowed after a non-function declarator
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(911): error C3484: syntax error: expected '->' before the return type
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(911): error C3613: missing return type after '->' ('int' assumed)
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(911): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(911): error C2146: syntax error: missing ';' before identifier 'ungetc'
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(912): error C2059: syntax error: 'return'
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(913): error C2059: syntax error: '}'
1>d:\workspace\trd\curl-7.61.0\projects\windows\vc14\curl_test\jwt-cpp\picojson.h(913): error C2143: syntax error: missing ';' before '}'
1>d:\workspace\vs2015\vc\include\xutility(2982): error C2143: syntax error: missing ';' before '{'
1>d:\workspace\vs2015\vc\include\xutility(2982): error C2447: '{': missing function header (old-style formal list?)

Multithreading application

Hello

I would like to know if your library is thread-safe because i intend to use it in a multithreading application. Right now I want to use your orginal library without making changes.

Do you use it in multithread application?

Thanks!

Best Regards!

Compilation errors - related to openssl version?

Good day, I'm still investigating this, but curious if you are aware of typecasting errors of this library and issues related to openssl version, possibly?

I am able to build your library and use it just fine, but I'm trying to integrate this into a 3rd party system and the build is failing on travis there. I am currently not sure if their VM is using different versions of libraries, but its on ubuntu (as am I).

I'll be digging in more, but if the error looks familiar, would love a hint. Maybe this fix is related?

../third_party/jwt-cpp/include/jwt-cpp/jwt.h: In function β€˜std::string jwt::helper::extract_pubkey_from_cert(const string&, const string&)’:
../third_party/jwt-cpp/include/jwt-cpp/jwt.h:77:87: error: invalid conversion from β€˜const void*’ to β€˜void*’ [-fpermissive]
    std::unique_ptr<BIO, decltype(&BIO_free_all)> certbio(BIO_new_mem_buf(certstr.data(), certstr.size()), BIO_free_all);
                                                                                       ^
In file included from /usr/include/openssl/evp.h:75:0,
                 from ../third_party/jwt-cpp/include/jwt-cpp/jwt.h:9,
                 from src/zm_crypt.h:27,
                 from /src/zm_user.cpp:32:
/usr/include/openssl/bio.h:668:6: error:   initializing argument 1 of β€˜BIO* BIO_new_mem_buf(void*, int)’ [-fpermissive]
 BIO *BIO_new_mem_buf(void *buf, int len);
      ^

Error: undefined reference to `EVP_sha256`

Code: https://github.com/GameTactic/CPP-Echo/blob/issue/19/src/main.cpp#L171-L172
OpenSSL: openssl version -a:

OpenSSL 1.1.1d  10 Sep 2019
built on: Tue Oct  8 20:54:30 2019 UTC
platform: debian-amd64
options:  bn(64,64) rc4(16x,int) des(int) blowfish(ptr) 
compiler: gcc -fPIC -pthread -m64 -Wa,--noexecstack -Wall -Wa,--noexecstack -g -O2 -fdebug-prefix-map=/build/openssl-jIn208/openssl-1.1.1d=. -specs=/usr/share/dpkg/no-pie-compile.specs -fstack-protector-strong -Wformat -Werror=format-security -DOPENSSL_USE_NODELETE -DL_ENDIAN -DOPENSSL_PIC -DOPENSSL_CPUID_OBJ -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DKECCAK1600_ASM -DRC4_ASM -DMD5_ASM -DVPAES_ASM -DGHASH_ASM -DECP_NISTZ256_ASM -DX25519_ASM -DPOLY1305_ASM -DNDEBUG -Wdate-time -D_FORTIFY_SOURCE=2
OPENSSLDIR: "/usr/lib/ssl"
ENGINESDIR: "/usr/lib/x86_64-linux-gnu/engines-1.1"
Seeding source: os-specific

Error when running make -j8:

/usr/bin/ld: CMakeFiles/server.dir/main.cpp.o: in function `jwt::helper::extract_pubkey_from_cert(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x2e): undefined reference to `BIO_new_mem_buf'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x36): undefined reference to `BIO_s_mem'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x3e): undefined reference to `BIO_new'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x51): undefined reference to `PEM_read_bio_X509'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x65): undefined reference to `X509_get_pubkey'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x7c): undefined reference to `PEM_write_bio_PUBKEY'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x9e): undefined reference to `BIO_ctrl'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0xc7): undefined reference to `EVP_PKEY_free'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0xcf): undefined reference to `X509_free'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0xdc): undefined reference to `BIO_free_all'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0xe9): undefined reference to `BIO_free_all'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x220): undefined reference to `EVP_PKEY_free'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x228): undefined reference to `X509_free'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x235): undefined reference to `BIO_free_all'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper24extract_pubkey_from_certERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x242): undefined reference to `BIO_free_all'
/usr/bin/ld: CMakeFiles/server.dir/main.cpp.o: in function `jwt::verifier<jwt::default_clock>::algo<jwt::algorithm::rs256>::verify(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
main.cpp:(.text._ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_[_ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_]+0x2e): undefined reference to `EVP_MD_CTX_new'
/usr/bin/ld: main.cpp:(.text._ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_[_ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_]+0x4a): undefined reference to `EVP_DigestInit'
/usr/bin/ld: main.cpp:(.text._ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_[_ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_]+0x62): undefined reference to `EVP_DigestUpdate'
/usr/bin/ld: main.cpp:(.text._ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_[_ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_]+0x7f): undefined reference to `EVP_VerifyFinal'
/usr/bin/ld: main.cpp:(.text._ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_[_ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_]+0x93): undefined reference to `EVP_MD_CTX_free'
/usr/bin/ld: main.cpp:(.text._ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_[_ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_]+0x185): undefined reference to `ERR_get_error'
/usr/bin/ld: main.cpp:(.text._ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_[_ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_]+0x18f): undefined reference to `ERR_error_string'
/usr/bin/ld: main.cpp:(.text._ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_[_ZN3jwt8verifierINS_13default_clockEE4algoINS_9algorithm5rs256EE6verifyERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESE_]+0x312): undefined reference to `EVP_MD_CTX_free'
/usr/bin/ld: CMakeFiles/server.dir/main.cpp.o: in function `jwt::helper::load_private_key_from_string(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
main.cpp:(.text._ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x14): undefined reference to `BIO_s_mem'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x1c): undefined reference to `BIO_new'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x30): undefined reference to `BIO_write'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x49): undefined reference to `PEM_read_bio_PrivateKey'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x68): undefined reference to `EVP_PKEY_free'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x9f): undefined reference to `BIO_free_all'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x14f): undefined reference to `BIO_free_all'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper28load_private_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x182): undefined reference to `EVP_PKEY_free'
/usr/bin/ld: CMakeFiles/server.dir/main.cpp.o: in function `jwt::helper::load_public_key_from_string(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
main.cpp:(.text._ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x2d): undefined reference to `BIO_s_mem'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x35): undefined reference to `BIO_new'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0xaf): undefined reference to `BIO_write'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0xde): undefined reference to `PEM_read_bio_PUBKEY'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0xfe): undefined reference to `EVP_PKEY_free'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x13a): undefined reference to `BIO_free_all'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x175): undefined reference to `BIO_write'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x20e): undefined reference to `ERR_get_error'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x218): undefined reference to `ERR_error_string'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x303): undefined reference to `BIO_free_all'
/usr/bin/ld: main.cpp:(.text._ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_[_ZN3jwt6helper27load_public_key_from_stringERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_]+0x322): undefined reference to `EVP_PKEY_free'
/usr/bin/ld: CMakeFiles/server.dir/main.cpp.o: in function `EchoServer::onMessage(std::weak_ptr<void>, std::shared_ptr<websocketpp::message_buffer::message<websocketpp::message_buffer::alloc::con_msg_manager> >)':
main.cpp:(.text._ZN10EchoServer9onMessageESt8weak_ptrIvESt10shared_ptrIN11websocketpp14message_buffer7messageINS4_5alloc15con_msg_managerEEEE[_ZN10EchoServer9onMessageESt8weak_ptrIvESt10shared_ptrIN11websocketpp14message_buffer7messageINS4_5alloc15con_msg_managerEEEE]+0x1091): undefined reference to `EVP_sha256'
collect2: error: ld returned 1 exit status
make[2]: *** [src/CMakeFiles/server.dir/build.make:84: src/server] Error 1
make[1]: *** [CMakeFiles/Makefile2:1032: src/CMakeFiles/server.dir/all] Error 2
make: *** [Makefile:130: all] Error 2

Support for RS512 algorithm

Hi,

When I tried to decode a token signed using RS512, I get the following error.

terminate called after throwing an instance of 'std::runtime_error'
  what():  Invalid input
Abort trap: 6

Does it support that.? I could see this library is marked as RS512 supported in jwt.io

jwt::verifier::verify() fails without private_key

Hi,
I am trying to verify a rs256 jwt token using the public key.
But it fails with the exception: failed to load public key: PEM_read_bio_PUBKEY failed.

Minimal code to reproduce: https://hastebin.com/niguvilewo.cpp (https://pastebin.com/Zb43pbHn)
If i change line 44 from .allow_algorithm(jwt::algorithm::rs256{ public_key }); to .allow_algorithm(jwt::algorithm::rs256{ public_key, private_key }); it works fine.

The key pair which i have used:
keys.zip

Add support for non-JSON payloads

I have a use case where I need to produce a JWT for non-JSON data and it would be nice to be able to use this library to achieve that.

random verification failure when using ECDSA with secp521r1

Using:

// g++ -std=c++14 -Ijwt-cpp/include main_ec3.cpp -lcrypto

#include "jwt-cpp/jwt.h"

int main()
{
#if 1
// Fails randomly

//openssl ecparam -genkey -name secp521r1 | openssl ec -out myec.pem
//openssl ec -in myec.pem -pubout -out myec_pub.pem

const std::string ec_private_key = R"key(-----BEGIN EC PRIVATE KEY-----
MIHcAgEBBEIAVNNl9RB5yK3ZqXjoWlVDI/I3CngB6dVePYBHaEw05IzpsMyxp9NA
i+1vivgl25JB0DPACVU+LZ51W3MF1iPiuP6gBwYFK4EEACOhgYkDgYYABADnMhAz
X7tNRt4lxi7Npi68P4/5CYQe718O2XQvav+Bv+Os55JT/v5l3wLkmOAvQzWgUBdx
dd/P81kw91YcJT4w6AC9GOdGZQXEaqmqZwTSTY5nVQ54ejfdAS9CywSCCwYnLgbW
bQZQD/q/opNUNUzfX7oiYAZsd9CKpDr1hL6kip19zg==
-----END EC PRIVATE KEY-----)key";
const std::string ec_public_key = R"key(-----BEGIN PUBLIC KEY-----
MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQA5zIQM1+7TUbeJcYuzaYuvD+P+QmE
Hu9fDtl0L2r/gb/jrOeSU/7+Zd8C5JjgL0M1oFAXcXXfz/NZMPdWHCU+MOgAvRjn
RmUFxGqpqmcE0k2OZ1UOeHo33QEvQssEggsGJy4G1m0GUA/6v6KTVDVM31+6ImAG
bHfQiqQ69YS+pIqdfc4=
-----END PUBLIC KEY-----)key";
#else
// Works reliably

//openssl ecparam -genkey -name secp256k1 | openssl ec -out myec.pem
//openssl ec -in myec.pem -pubout -out myec_pub.pem

const std::string ec_private_key = R"(-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgPGJGAm4X1fvBuC1z
SpO/4Izx6PXfNMaiKaS5RUkFqEGhRANCAARCBvmeksd3QGTrVs2eMrrfa7CYF+sX
sjyGg+Bo5mPKGH4Gs8M7oIvoP9pb/I85tdebtKlmiCZHAZE5w4DfJSV6
-----END PRIVATE KEY-----)";
const std::string ec_public_key = R"(-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEQgb5npLHd0Bk61bNnjK632uwmBfr
F7I8hoPgaOZjyhh+BrPDO6CL6D/aW/yPObXXm7SpZogmRwGROcOA3yUleg==
-----END PUBLIC KEY-----)";
#endif

if (false)
{
auto token = jwt::create()
.set_issuer("auth0")
.set_type("JWS")
.set_payload_claim("sample", jwt::claim(std::string("test")))
.sign(jwt::algorithm::es256{"", ec_private_key});
auto decoded = jwt::decode(token);

auto verifier = jwt::verify()
  .allow_algorithm(jwt::algorithm::es256{ ec_public_key })
  .with_issuer("auth0");

verifier.verify(decoded);

}
else
{
std::string hash = "012345678901234567890123456789012";

const jwt::algorithm::es256 signer("", ec_private_key);

const auto signature = signer.sign(hash);

const jwt::algorithm::es256 verifier(ec_public_key);

verifier.verify(hash, signature);

}
}
I observe random verification failures:

g++ -std=c++14 -Ijwt-cpp/include main_ec3.cpp -lcrypto
[ixdevenv] abgengcluster:/home/adesitter/MR2/EC_signing_verify>./a.out
[ixdevenv] abgengcluster:/home/adesitter/MR2/EC_signing_verify>./a.out
[ixdevenv] abgengcluster:/home/adesitter/MR2/EC_signing_verify>./a.out
[ixdevenv] abgengcluster:/home/adesitter/MR2/EC_signing_verify>./a.out
[ixdevenv] abgengcluster:/home/adesitter/MR2/EC_signing_verify>./a.out
[ixdevenv] abgengcluster:/home/adesitter/MR2/EC_signing_verify>./a.out
[ixdevenv] abgengcluster:/home/adesitter/MR2/EC_signing_verify>./a.out
terminate called after throwing an instance of 'jwt::signature_verification_exception'
what(): Invalid signature
Abort
g++ -std=c++14 -Ijwt-cpp/include main_ec3.cpp -lcrypto
./a.out
./a.out
./a.out
./a.out
./a.out
terminate called after throwing an instance of 'jwt::signature_verification_exception'
what(): Invalid signature
Abort

Fix Unittests for PSS token generation

PSS adds salt to the generated signature, so simply signing a known token and check for a specific result (as done in all other test cases) is not possible. We need to find a way to check if a given signature is in the expected format. Ideally, we could somehow force OpenSSL to always use the same salt.

cppcheck warnnings

I found some cppcheck warnnings bellow, please help to see whether this this can be fixed:

yum install cppcheck -y

cppcheck --enable=all --quiet --std=c++11 --platform=native .

[common/jwt-cpp/base.h:99]: (style) Unused private function: 'base::decode'
[common/jwt-cpp/picojson.h:964]: (style) Class 'default_parse_context' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:620]: (style) Struct 'rs256' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:635]: (style) Struct 'rs384' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:650]: (style) Struct 'rs512' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:665]: (style) Struct 'es256' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:680]: (style) Struct 'es384' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:695]: (style) Struct 'es512' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:711]: (style) Struct 'ps256' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:726]: (style) Struct 'ps384' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:741]: (style) Struct 'ps512' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:780]: (style) Class 'claim' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:783]: (style) Class 'claim' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:786]: (style) Class 'claim' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/jwt.h:789]: (style) Class 'claim' has a constructor with 1 argument that is not explicit.
[common/jwt-cpp/picojson.h:711]: (style) The scope of the variable 'hex' can be reduced.

Can I decode passwd from token

Hi Dear,

I am creating token with this way:

	auto token = jwt::create()
		.set_issuer(HTTP_HEADER_JWT_ISSUER)
		.set_type(HTTP_HEADER_JWT)
		.set_issued_at(jwt::date(std::chrono::system_clock::now()))
		.set_expires_at(jwt::date(std::chrono::system_clock::now() + std::chrono::seconds{ timeoutSeconds }))
		.set_payload_claim(HTTP_HEADER_JWT_name, jwt::claim(uname))
		.sign(jwt::algorithm::hs256{ passwd });
	return std::move(token);

and verify user token like this:

		auto decoded_token = jwt::decode(token);
		auto verifier = jwt::verify()
			.allow_algorithm(jwt::algorithm::hs256{ userKey })
			.with_issuer(HTTP_HEADER_JWT_ISSUER)
			.with_claim(HTTP_HEADER_JWT_name, userName);
		verifier.verify(decoded_token);

If I want to use LDAP for password check so I do not have userKey here, can I decode passwd from token from decoded_token ?

Thanks a lot!

How to determine if verification is successful or not?

From the code, the following is the way to verify a token.

void verify(std::string some_token)
{
	auto verifier = jwt::verify().allow_algorithm(jwt::algorithm::hs256{ "secret" }).with_issuer("auth0");

	verifier.verify(jwt::decode(some_token));
}

if this function is called, @Thalhammer , please how can the status of the verification be determined since the function returns a void (because verifier.verify() return void).

Thanks.

Claim class constructor

Hi,

I have been using this library for a while, and I do not understand why the claim class has not a constructor for an array of numbers (int, int64, double, etc). The type of the claim can be an array, but only an array of strings. Is for some reason that I do not understand?

Regards,
J. A.

std::bad_cast for one audience case

According to the spec,

In the special case when the JWT has one audience, the aud value MAY be a
single case-sensitive string containing a StringOrURI value.

so, the aud claim may be either a string or an array of strings.

Another token expiry issue

Hi, thanks for this library. I'm pretty new to JWT as well as C++. I looked at this issue - not sure if its the same problem.

I'm trying a simple example:

  • Generate a token for 10 minutes (token generation works, not sure about time)
  • Decode token to describe claims (works)
  • verify token immediately (says token expires)

Would appreciate if you could spot an issue. Thanks.

Output:

Time now is: 2019-05-03T18:27:28Z
Encoded token:eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NTY5MjY2NDgsImlhdCI6MTU1NjkyNjA0OCwiaXNzIjoiYXV0aDAifQ._0pFMLEtcvB
HUR_T33eMV-l3n5pG1NRx_pIPmhHMW90
Decoded token details:iss = "auth0"
exp = 1556926648
iat = 1556926048
Validation results:oops exception:token verification failed: token expired

Code:

#include "include/jwt-cpp/jwt.h"
#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>



#define EXPIRY_MIN 10

std::string now_time()
{
  std::time_t now= std::time(0);
  std::tm* now_tm= std::gmtime(&now);
  char buf[100];
  std::strftime(buf, 100, "%Y-%m-%dT%H:%M:%SZ", now_tm);
  return buf;
}

int main(int argc, const char** argv) {
        std::tm tm = {};
        std::string now = now_time();
        std::cout << "Time now is: " << now << std::endl;
        std::istringstream iss(now);
        iss >> std::get_time(&tm, "%Y-%m-%dT%H:%M:%SZ");

        auto tp = std::chrono::system_clock::from_time_t(std::mktime(&tm));
        auto expiresAt = tp+std::chrono::minutes(EXPIRY_MIN);



        auto token = jwt::create()
                        .set_issuer("auth0")
                        .set_expires_at(jwt::date(expiresAt))
                        .set_issued_at(jwt::date(tp))
                        .sign(jwt::algorithm::hs256{"secret"});



        std::cout << "Encoded token:" << token << std::endl;

        std::cout << "Decoded token details:";
        auto decoded = jwt::decode(token);
        for(auto& e : decoded.get_payload_claims())
                std::cout << e.first << " = " << e.second.to_json() << std::endl;

        std::cout << "Validation results:";
        auto verifier = jwt::verify()
                        .allow_algorithm(jwt::algorithm::hs256{ "secret" })
                        .with_issuer("auth0");

        try {
                verifier.verify(decoded);
        }
        catch (const std::exception &exc) {
                std::cerr << "oops exception:" << exc.what() << std::endl;
        }
}

PS256, PS384, PS512 Support

We should support PS256, PS384 and PS512 support,
however, I currently do not have the time to check out how to do this using OpenSSL.

validating issued_at alway return token expired?

if (jwt.has_issued_at()) { auto leeway = claims.count("iat") == 1 ? std::chrono::system_clock::to_time_t(claims.at("iat").as_date()) : default_leeway; auto iat = jwt.get_issued_at(); if (time < iat - std::chrono::seconds(leeway)) throw token_verification_exception("token expired"); }

leeway = 0 so time < iat! who else got this ?

Can jwt::builder::sign() be const?

It would be nice if the std::string jwt::builder::sign(const T& algo) method could be const.

From what I can determine, the only reason that it is not const is that set_algorithm() is being called to set the 'alg' claim.

Is there any reason that the 'alg' claim cannot be added directly to obj_header instead of modifying this?

Am I missing some design element?

Error in README.md example

Currently says:
Creating a token (and signing) is equally easy.

auto token = jwt::create()
	.set_issuer("auth0")
	.set_type("JWS")
	.set_payload_claim("sample", std::string("test"))
	.sign(jwt::algorithm::hs256{"secret"});

Error:
The set_payload_claim function takes a jwt::claim as its 2nd argument.

Should say:
Creating a token (and signing) is equally easy.

auto token = jwt::create()
	.set_issuer("auth0")
	.set_type("JWS")
	.set_payload_claim("sample", jwt::claim(std::string("test")))
	.sign(jwt::algorithm::hs256{"secret"});

Creating Jwt with private key

Hi,
Thanks for creating this library. It is really a great help for implementing oidc.
I was not able to create jwt token with private key. I wanted to set the following parameters :
1.authority
2.redirecturl
3. sessionid ot state
4. privatekey

can you please share a sample if the library can support the above parameters.

How to support JWT token logoff

When use JWT authentication for WEB access control, JWT can create token with expire time, after the token is generated, the expire time is fixed, how to implement a 'logoff' (expire immediately) behavior within the token.

Thanks.

warning C4458: declaration of 'pkey' hides class member and warning C4267: 'initializing': conversion from 'size_t' to 'uint32_t'

Hi,

I just compile the latest version on MVSC with warning level 4 due to my project and I find out a redeclaration name of a variable at line 320 and some possibile loss of data.

I think for the first one should be enough to change the variable because is local, for the second I think some more static cast should be fine.

What do you think about?

Thank you in advance.

Build fails with werror

Hey, thanks for great library. I've had some issues to use jwt.h with gcc 7.3 c++17 and werror.

  • line 269: static_cast<uint8_t>(raw[0]) is needed as char is signed
  • line 618: implicit fallthrough - [[fallthrough]] attribute is needed in each case for cpp17
  • line 716: virtual ~algo_base() = default; is missing

Packaging (RPM, DEB)

It would be great if this software would be available as rpm and deb packages, to allow other software depending on it to be built in a clean sandbox.

Api referece - documentation

Where can I find some api referece and some examples? for example: how to use with rsa public and private key

Not working when compiled but working on visual studio

Hi,

Maybe you know where my problem come from, the verification for the token work when i test on visual studio, but then, when i've compiled and test from the compiled code, the token is always false.

Maybe some missed links for the compiled code and the function return an error or something ?
Thanks for you help.

Cmake configure with -DEXTERNAL_PICOJSON fails

Hi, when building with -DEXTERNAL_PICOJSON, my build fails to find the necessary cmake configuration to find the external picojson library:

$ cmake /dev/shm/duncan.macleod/conda/conda-bld/jwt-cpp_1590139493710/work -DBUILD_TESTS:BOOL=TRUE -DCMAKE_INSTALL_PREFIX:PATH=/dev/shm/duncan.macleod/conda/conda-bld/jwt-cpp_1590139493710/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placeh -DEXTERNAL_PICOJSON:BOOL=TRUE
-- The C compiler identification is GNU 4.8.5
-- The CXX compiler identification is GNU 4.8.5
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc - works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ - works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found OpenSSL: $PREFIX/lib/libcrypto.so (found suitable version "1.1.1g", minimum required is "1.0.2")
CMake Error at CMakeLists.txt:17 (find_package):
  By not providing "Findpicojson.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "picojson",
  but CMake did not find one.

  Could not find a package configuration file provided by "picojson" with any
  of the following names:

    picojsonConfig.cmake
    picojson-config.cmake

  Add the installation prefix of "picojson" to CMAKE_PREFIX_PATH or set
  "picojson_DIR" to a directory containing one of the above files.  If
  "picojson" provides a separate development package or SDK, be sure it has
  been installed.


-- Configuring incomplete, errors occurred!
See also "$SRC_DIR/_build/CMakeFiles/CMakeOutput.log".

I'm pretty sure picojson doesn't provide its own cmake configuration files, so I'm not sure how to proceed (other than patching the build).

signature verification failed

Hi, I have an need to verify the token generated through JAVA API in C++ jwt verification. Now the issue is, the signature generated in C++ and JAVA are different when using the same algorithm, data and secret code.

Can anyone let me know if we have issue verifying the token generated in two different programming languages.

β€œalg”: β€œHS512”
β€œname”: β€œTest”
secret key = β€œ12345678901234567890”

Thanks in advance

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.