diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..2a60a0a --- /dev/null +++ b/.clang-format @@ -0,0 +1,22 @@ +BasedOnStyle: LLVM +BreakBeforeBraces: Attach + +ColumnLimit: 120 # Match GitHub UI + +UseTab: Always +TabWidth: 4 +IndentWidth: 4 +AccessModifierOffset: -4 +ContinuationIndentWidth: 4 +NamespaceIndentation: All +IndentCaseLabels: false + +PointerAlignment: Left +AlwaysBreakTemplateDeclarations: Yes +SpaceAfterTemplateKeyword: false +AllowShortCaseLabelsOnASingleLine: true +AllowShortIfStatementsOnASingleLine: WithoutElse +AllowShortBlocksOnASingleLine: Always + +FixNamespaceComments: true +ReflowComments: false diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..33af44c --- /dev/null +++ b/.editorconfig @@ -0,0 +1,17 @@ +root = true + +[!*.{h,cpp}] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.{h,cpp}] +indent_style = tab +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/actions/install/gtest/action.yml b/.github/actions/install/gtest/action.yml index f7fd09b..11a6c5f 100644 --- a/.github/actions/install/gtest/action.yml +++ b/.github/actions/install/gtest/action.yml @@ -3,13 +3,13 @@ description: Install and setup GTest for linking and building test application runs: using: composite steps: - - run: sudo apt-get install libgtest-dev lcov - shell: bash - - run: (cd /usr/src/gtest && sudo `which cmake` .) - shell: bash - - run: sudo make -j $(nproc) -C /usr/src/gtest - shell: bash - - run: sudo ln -s /usr/src/gtest/libgtest.a /usr/lib/libgtest.a - shell: bash - - run: sudo ln -s /usr/src/gtest/libgtest_main.a /usr/lib/libgtest_main.a - shell: bash + - run: sudo apt-get install libgtest-dev lcov + shell: bash + - run: (cd /usr/src/gtest && sudo `which cmake` .) + shell: bash + - run: sudo make -j $(nproc) -C /usr/src/gtest + shell: bash + - run: sudo ln -s /usr/src/gtest/libgtest.a /usr/lib/libgtest.a + shell: bash + - run: sudo ln -s /usr/src/gtest/libgtest_main.a /usr/lib/libgtest_main.a + shell: bash diff --git a/.github/actions/install/jsoncons/action.yml b/.github/actions/install/jsoncons/action.yml index daca91a..4393a14 100644 --- a/.github/actions/install/jsoncons/action.yml +++ b/.github/actions/install/jsoncons/action.yml @@ -4,15 +4,15 @@ inputs: version: description: The desired jsoncons version to install required: false - default: '0.159.0' + default: "0.159.0" runs: using: composite steps: - - run: | - cd /tmp - wget https://github.com/danielaparker/jsoncons/archive/v${{ inputs.version }}.tar.gz - tar -zvxf /tmp/v${{ inputs.version }}.tar.gz - cd jsoncons-${{ inputs.version }} - cmake . - sudo cmake --install . - shell: bash + - run: | + cd /tmp + wget https://github.com/danielaparker/jsoncons/archive/v${{ inputs.version }}.tar.gz + tar -zvxf /tmp/v${{ inputs.version }}.tar.gz + cd jsoncons-${{ inputs.version }} + cmake . + sudo cmake --install . + shell: bash diff --git a/.github/actions/install/libressl/action.yml b/.github/actions/install/libressl/action.yml index 806ca7c..709ad70 100644 --- a/.github/actions/install/libressl/action.yml +++ b/.github/actions/install/libressl/action.yml @@ -4,16 +4,16 @@ inputs: version: description: The desired LibreSSL version to install required: false - default: '3.3.0' + default: "3.3.0" runs: using: composite steps: - - run: | - wget https://raw.githubusercontent.com/libressl-portable/portable/v${{ inputs.version }}/FindLibreSSL.cmake -P cmake/ - cd /tmp - wget https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-${{ inputs.version }}.tar.gz - tar -zvxf /tmp/libressl-${{ inputs.version }}.tar.gz - cd libressl-${{ inputs.version }} - ./configure - sudo make -j $(nproc) install - shell: bash + - run: | + wget https://raw.githubusercontent.com/libressl-portable/portable/v${{ inputs.version }}/FindLibreSSL.cmake -P cmake/ + cd /tmp + wget https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-${{ inputs.version }}.tar.gz + tar -zvxf /tmp/libressl-${{ inputs.version }}.tar.gz + cd libressl-${{ inputs.version }} + ./configure + sudo make -j $(nproc) install + shell: bash diff --git a/.github/logo.svg b/.github/logo.svg new file mode 100644 index 0000000..63017cb --- /dev/null +++ b/.github/logo.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index da51da7..cff18ff 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -1,119 +1,120 @@ -name: CMake Integration CI +name: CMake CI on: push: - branches: [ master ] + branches: [master] pull_request: - branches: [ master ] + branches: [master] paths: - - 'CMakeLists.txt' - - 'include/jwt-cpp/**' - - 'tests/cmake/**' - - '.github/workflows/cmake.yml' + - "CMakeLists.txt" + - "include/jwt-cpp/**" + - "tests/cmake/**" + - ".github/actions/**" + - ".github/workflows/cmake.yml" jobs: min-req: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: install cmake - run: | - wget https://cmake.org/files/v3.8/cmake-3.8.2.tar.gz - tar -zxf cmake-3.8.2.tar.gz - cd cmake-3.8.2 - ./bootstrap && make -j $(nproc) && sudo make install + - uses: actions/checkout@v2 + - name: install cmake + run: | + wget https://cmake.org/files/v3.8/cmake-3.8.2.tar.gz + tar -zxf cmake-3.8.2.tar.gz + cd cmake-3.8.2 + ./bootstrap && make -j $(nproc) && sudo make install - - name: setup - run: | - mkdir build - cd build - cmake .. -DJWT_BUILD_EXAMPLES=OFF - sudo make install + - name: setup + run: | + mkdir build + cd build + cmake .. -DJWT_BUILD_EXAMPLES=OFF + sudo make install - - name: test - run: | - cd tests/cmake - cmake . -DCMAKE_PREFIX_PATH=/usr/local/cmake -DTEST:STRING="defaults-enabled" - cmake --build . + - name: test + run: | + cd tests/cmake + cmake . -DCMAKE_PREFIX_PATH=/usr/local/cmake -DTEST:STRING="defaults-enabled" + cmake --build . custom-install: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: install cmake - uses: lukka/get-cmake@latest + - uses: actions/checkout@v2 + - name: install cmake + uses: lukka/get-cmake@latest - - name: setup - run: | - mkdir build - cd build - cmake .. -DCMAKE_INSTALL_PREFIX:STRING="/opt/jwt-cpp" -DJWT_BUILD_EXAMPLES=OFF - make install + - name: setup + run: | + mkdir build + cd build + cmake .. -DCMAKE_INSTALL_PREFIX:STRING="/opt/jwt-cpp" -DJWT_BUILD_EXAMPLES=OFF + make install - - name: test - run: | - cd tests/cmake - cmake . -DCMAKE_PREFIX_PATH=/opt/jwt-cpp/cmake -DTEST:STRING="defaults-enabled" - cmake --build . + - name: test + run: | + cd tests/cmake + cmake . -DCMAKE_PREFIX_PATH=/opt/jwt-cpp/cmake -DTEST:STRING="defaults-enabled" + cmake --build . no-pico: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: install cmake - uses: lukka/get-cmake@latest + - uses: actions/checkout@v2 + - name: install cmake + uses: lukka/get-cmake@latest - - name: setup - run: | - mkdir build - cd build - cmake .. -DJWT_DISABLE_PICOJSON=ON -DJWT_BUILD_EXAMPLES=OFF - sudo make install + - name: setup + run: | + mkdir build + cd build + cmake .. -DJWT_DISABLE_PICOJSON=ON -DJWT_BUILD_EXAMPLES=OFF + sudo make install - - name: test - run: | - cd tests/cmake - cmake . -DCMAKE_PREFIX_PATH=/usr/local/cmake -DTEST:STRING="picojson-is-disabled" - cmake --build . + - name: test + run: | + cd tests/cmake + cmake . -DCMAKE_PREFIX_PATH=/usr/local/cmake -DTEST:STRING="picojson-is-disabled" + cmake --build . no-base64: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: install cmake - uses: lukka/get-cmake@latest + - uses: actions/checkout@v2 + - name: install cmake + uses: lukka/get-cmake@latest - - name: setup - run: | - mkdir build - cd build - cmake .. -DJWT_DISABLE_BASE64=ON -DJWT_BUILD_EXAMPLES=OFF - sudo make install + - name: setup + run: | + mkdir build + cd build + cmake .. -DJWT_DISABLE_BASE64=ON -DJWT_BUILD_EXAMPLES=OFF + sudo make install - - name: test - run: | - cd tests/cmake - cmake . -DCMAKE_PREFIX_PATH=/usr/local/cmake -DTEST:STRING="base64-is-disabled" - cmake --build . + - name: test + run: | + cd tests/cmake + cmake . -DCMAKE_PREFIX_PATH=/usr/local/cmake -DTEST:STRING="base64-is-disabled" + cmake --build . with-libressl: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: install cmake - uses: lukka/get-cmake@latest - - name: install libressl - uses: ./.github/actions/install/libressl + - uses: actions/checkout@v2 + - name: install cmake + uses: lukka/get-cmake@latest + - name: install libressl + uses: ./.github/actions/install/libressl - - name: setup - run: | - mkdir build - cd build - cmake .. -DJWT_SSL_LIBRARY:STRING="LibreSSL" -DJWT_BUILD_EXAMPLES=OFF - sudo make install + - name: setup + run: | + mkdir build + cd build + cmake .. -DJWT_SSL_LIBRARY:STRING="LibreSSL" -DJWT_BUILD_EXAMPLES=OFF + sudo make install - - name: test - run: | - cd tests/cmake - cmake . -DCMAKE_PREFIX_PATH=/usr/local/cmake -DCMAKE_MODULE_PATH=../../cmake -DTEST:STRING="libressl-is-used" - cmake --build . + - name: test + run: | + cd tests/cmake + cmake . -DCMAKE_PREFIX_PATH=/usr/local/cmake -DCMAKE_MODULE_PATH=../../cmake -DTEST:STRING="libressl-is-used" + cmake --build . diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 3313800..c7583ee 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -2,38 +2,36 @@ name: Coverage CI on: push: - branches: [ master ] + branches: [master] pull_request: - branches: [ master ] + branches: [master] paths: - - 'CMakeLists.txt' - - 'include/jwt-cpp/**' - - 'tests/*' - - '.github/workflows/coverate.yml' + - "CMakeLists.txt" + - "include/jwt-cpp/**" + - "tests/*" + - ".github/actions/**" + - ".github/workflows/coverate.yml" jobs: build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: install cmake - uses: lukka/get-cmake@latest - - name: install gtest - uses: ./.github/actions/install/gtest + - uses: actions/checkout@v2 + - uses: lukka/get-cmake@latest + - uses: ./.github/actions/install/gtest - - name: configure - run: | - mkdir build - cd build - cmake .. -DJWT_BUILD_TESTS=ON -DJWT_ENABLE_COVERAGE=ON -DCMAKE_BUILD_TYPE=Debug - - - name: make - run: cd build && make jwt-cpp-test coverage - - - name: Coveralls GitHub Action - uses: coverallsapp/github-action@v1.1.1 - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - path-to-lcov: build/coverage.info + - name: configure + run: | + mkdir build + cd build + cmake .. -DJWT_BUILD_EXAMPLES=OFF -DJWT_BUILD_TESTS=ON -DJWT_ENABLE_COVERAGE=ON -DCMAKE_BUILD_TYPE=Debug + + - name: run + run: | + cd build + make jwt-cpp-test coverage + + - uses: coverallsapp/github-action@v1.1.1 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + path-to-lcov: build/coverage.info diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml index dbe0a00..aa3aebf 100644 --- a/.github/workflows/documentation.yml +++ b/.github/workflows/documentation.yml @@ -2,20 +2,18 @@ name: Documentation CI on: push: - branches: [ master ] + branches: [master] jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - - name: run doxygen - uses: mattnotmitt/doxygen-action@v1 - - - name: deploy - uses: peaceiris/actions-gh-pages@v3 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ./docs/html - force_orphan: true + - uses: actions/checkout@v2 + - name: run doxygen + uses: mattnotmitt/doxygen-action@v1 + - name: deploy + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./docs/html + force_orphan: true diff --git a/.github/workflows/libresssl.yml b/.github/workflows/libresssl.yml index 8a5136a..8def428 100644 --- a/.github/workflows/libresssl.yml +++ b/.github/workflows/libresssl.yml @@ -2,14 +2,15 @@ name: LibreSSL CI on: push: - branches: [ master ] + branches: [master] pull_request: - branches: [ master ] + branches: [master] paths: - - 'CMakeLists.txt' - - 'include/jwt-cpp/**' - - 'tests/*' - - '.github/workflows/libressl.yml' + - "CMakeLists.txt" + - "include/jwt-cpp/**" + - "tests/*" + - ".github/actions/**" + - ".github/workflows/libressl.yml" jobs: build: @@ -18,44 +19,40 @@ jobs: matrix: libressl: ["3.3.0", "3.2.2"] steps: - - uses: actions/checkout@v2 - - name: install cmake - uses: lukka/get-cmake@latest - - name: install gtest - uses: ./.github/actions/install/gtest - - name: install libressl - uses: ./.github/actions/install/libressl - with: - version: ${{ matrix.libressl }} + - uses: actions/checkout@v2 + - uses: lukka/get-cmake@latest + - uses: ./.github/actions/install/gtest + - uses: ./.github/actions/install/libressl + with: + version: ${{ matrix.libressl }} - - name: configure - run: cmake . -DJWT_BUILD_TESTS=ON -DJWT_SSL_LIBRARY:STRING=LibreSSL + - name: configure + run: cmake . -DJWT_BUILD_TESTS=ON -DJWT_SSL_LIBRARY:STRING=LibreSSL - - name: make - run: make + - run: make - - name: test - run: ./tests/jwt-cpp-test + - name: test + run: ./tests/jwt-cpp-test - - name: badge success - if: github.event_name == 'push' && success() - run: | - mkdir -p badges/libressl/${{ matrix.libressl }} - echo '{ "schemaVersion": 1, "label": "${{ matrix.libressl }}", "message": "Passing", "color": "brightgreen" }' > badges/libressl/${{ matrix.libressl }}/shields.json + - name: badge success + if: github.event_name == 'push' && success() + run: | + mkdir -p badges/libressl/${{ matrix.libressl }} + echo '{ "schemaVersion": 1, "label": "${{ matrix.libressl }}", "message": "Passing", "color": "brightgreen" }' > badges/libressl/${{ matrix.libressl }}/shields.json - - name: badge failure - if: github.event_name == 'push' && !success() - run: | - mkdir -p badges/libressl/${{ matrix.libressl }} - echo '{ "schemaVersion": 1, "label": "${{ matrix.libressl }}", "message": "Failing", "color": "red" }' > badges/libressl/${{ matrix.libressl }}/shields.json + - name: badge failure + if: github.event_name == 'push' && !success() + run: | + mkdir -p badges/libressl/${{ matrix.libressl }} + echo '{ "schemaVersion": 1, "label": "${{ matrix.libressl }}", "message": "Failing", "color": "red" }' > badges/libressl/${{ matrix.libressl }}/shields.json - - name: badge publish - if: github.event_name == 'push' - uses: peaceiris/actions-gh-pages@v3 - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_branch: badges - publish_dir: ./badges - keep_files: true - user_name: 'github-actions[bot]' - user_email: 'github-actions[bot]@users.noreply.github.com' + - name: badge publish + if: github.event_name == 'push' + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_branch: badges + publish_dir: ./badges + keep_files: true + user_name: "github-actions[bot]" + user_email: "github-actions[bot]@users.noreply.github.com" diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..81c8678 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,23 @@ +name: Lint CI + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + paths: + - 'include/jwt-cpp/**.h' + - 'tests/**.cpp' + - '.github/workflows/lint.yml' + +jobs: + cpp: + runs-on: ubuntu-20.04 + strategy: + matrix: + files: ["include/jwt-cpp/*.h", "tests/**.cpp"] + steps: + - run: sudo apt-get install clang-format-10 + - uses: actions/checkout@v2 + - run: clang-format-10 -i ${{ matrix.files }} + - run: exit $(git status -s | wc -l) diff --git a/.github/workflows/traits.yml b/.github/workflows/traits.yml index 31af8fe..b60c77f 100644 --- a/.github/workflows/traits.yml +++ b/.github/workflows/traits.yml @@ -2,29 +2,35 @@ name: Traits CI on: push: - branches: [ master ] + branches: [master] pull_request: - branches: [ master ] + branches: [master] + paths: + - "CMakeLists.txt" + - "include/jwt-cpp/**" + - "tests/jsoncons/**" + - ".github/actions/**" + - ".github/workflows/traits.yml" jobs: jsoncons: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: lukka/get-cmake@latest - - uses: ./.github/actions/install/gtest - - uses: ./.github/actions/install/jsoncons + - uses: actions/checkout@v2 + - uses: lukka/get-cmake@latest + - uses: ./.github/actions/install/gtest + - uses: ./.github/actions/install/jsoncons - - name: setup - run: | - mkdir build - cd build - cmake .. -DJWT_BUILD_EXAMPLES=OFF - sudo make install + - name: setup + run: | + mkdir build + cd build + cmake .. -DJWT_BUILD_EXAMPLES=OFF + sudo make install - - name: configure - run: | - cd tests/jsoncons - cmake . -DCMAKE_PREFIX_PATH=/usr/local/cmake - cmake --build . - ./jsoncons-traits-narrow + - name: test + run: | + cd tests/jsoncons + cmake . -DCMAKE_PREFIX_PATH=/usr/local/cmake + cmake --build . + ./jsoncons-traits-narrow diff --git a/CMakeLists.txt b/CMakeLists.txt index 6a5ae1c..9c01d0c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,7 +17,7 @@ set_property(CACHE JWT_SSL_LIBRARY PROPERTY STRINGS ${JWT_SSL_LIBRARY_OPTIONS}) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake") if(NOT JWT_SSL_LIBRARY IN_LIST JWT_SSL_LIBRARY_OPTIONS) - message(FATAL_ERROR "JWT_SSL_LIBRARY must be one of ${JWT_SSL_LIBRARY_OPTIONS}") + message(FATAL_ERROR "JWT_SSL_LIBRARY must be one of ${JWT_SSL_LIBRARY_OPTIONS}") endif() if(${JWT_SSL_LIBRARY} MATCHES "OpenSSL") diff --git a/README.md b/README.md index cf9aa54..9420668 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# jwt-cpp +# ![logo](https://raw.githubusercontent.com/prince-chrismc/jwt-cpp/linting-and-maintance/.github/logo.svg) [![License Badge](https://img.shields.io/github/license/Thalhammer/jwt-cpp)](https://github.com/Thalhammer/jwt-cpp/blob/master/LICENSE) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/5f7055e294744901991fd0a1620b231d)](https://app.codacy.com/app/Thalhammer/jwt-cpp?utm_source=github.com&utm_medium=referral&utm_content=Thalhammer/jwt-cpp&utm_campaign=Badge_Grade_Settings) @@ -7,12 +7,13 @@ [![Documentation Badge](https://img.shields.io/badge/Documentation-master-blue)](https://thalhammer.github.io/jwt-cpp/) [![Stars Badge](https://img.shields.io/github/stars/Thalhammer/jwt-cpp)](https://github.com/Thalhammer/jwt-cpp/stargazers) -A header only library for creating and validating [JSON Web Tokens](https://tools.ietf.org/html/rfc7519) in C++11. For a great introduction, [read this](https://jwt.io/introduction/) +A header only library for creating and validating [JSON Web Tokens](https://tools.ietf.org/html/rfc7519) in C++11. For a great introduction, [read this](https://jwt.io/introduction/). ## Signature algorithms -jwt-cpp supports all algorithms defined by the spec. The modular design of jwt-cpp allows one to add additional algorithms without any problems. If you need any feel free to open a pull request. -For the sake of completeness, here is a list of all supported algorithms: +jwt-cpp supports all the algorithms defined by the specifications. The modular design allows to easily add additional algorithms without any problems. If you need any feel free to create a pull request or [open an issue](https://github.com/Thalhammer/jwt-cpp/issues/new). + +For completeness, here is a list of all supported algorithms: | HMSC | RSA | ECDSA | PSS | EdDSA | | ----- | ----- | ----- | ----- | ------- | @@ -22,8 +23,7 @@ For the sake of completeness, here is a list of all supported algorithms: ## SSL Compatability -In the name of flexibility and extensibility, jwt-cpp supports both [OpenSSL](https://github.com/openssl/openssl) and [LibreSSL](https://github.com/libressl-portable/portable). -These are the version which are tested: +In the name of flexibility and extensibility, jwt-cpp supports both [OpenSSL](https://github.com/openssl/openssl) and [LibreSSL](https://github.com/libressl-portable/portable). These are the version which are, or have been, tested: | OpenSSL | LibreSSL | | -------------- | --------------- | @@ -38,13 +38,13 @@ These are the version which are tested: ## Overview -Since 0.5.0-rc.0, there is no hard dependency on a JSON library; instead there's a generic `jwt::basic_claim` which is templated around the types required.It requires a traits type, which defines types for a value, object, array, string, number, integer and boolean, as well as methods to translate between them. +There is no hard dependency on a JSON library. Instead, there's a generic `jwt::basic_claim` which is templated around type traits, which described the semantic [JSON types](https://json-schema.org/understanding-json-schema/reference/type.html) for a value, object, array, string, number, integer and boolean, as well as methods to translate between them. ```cpp jwt::basic_claim claim(json::object({{"json", true},{"example", 0}})); ``` -This allows for complete freedom when picking which libraries you want to use. For more information, [see below](#providing-your-own-json-traits-your-traits) +This allows for complete freedom when picking which libraries you want to use. For more information, [see below](#providing-your-own-json-traits-your-traits). In order to maintain compatibility, [picojson](https://github.com/kazuho/picojson) is still used to provide a specialized `jwt::claim` along with all helpers. Defining `JWT_DISABLE_PICOJSON` will remove this optional dependency. @@ -52,7 +52,7 @@ As for the base64 requirements of JWTs, this libary provides `base.h` with all t ### Getting Started -Simple example of decoding a token and printing all claims ([try it out](https://github.com/Thalhammer/jwt-cpp/tree/master/example/print-claims.cpp)): +Simple example of decoding a token and printing all [claims](https://tools.ietf.org/html/rfc7519#section-4) ([try it out](https://github.com/Thalhammer/jwt-cpp/tree/master/example/print-claims.cpp)): ```cpp #include @@ -111,6 +111,8 @@ There are several key items that need to be provided to a `jwt::basic_claim` in If ever you are not sure, the traits are heavily checked against static asserts to make sure you provide everything that's required. +> :warning: Not all JSON libraries are a like, you may need to extent certain types such that it can be used by jwt-cpp. See this [example](https://github.com/Thalhammer/jwt-cpp/blob/ac3de9e69bc698a464dacb256a1b50512843f092/tests/jsoncons/JsonconsTest.cpp). + ```cpp struct my_favorite_json_library_traits { // Type Specifications diff --git a/cmake/code-coverage.cmake b/cmake/code-coverage.cmake index fd7da29..5e630bc 100644 --- a/cmake/code-coverage.cmake +++ b/cmake/code-coverage.cmake @@ -1,15 +1,12 @@ set(COVERAGE_CMAKE "${CMAKE_BINARY_DIR}/cmake/CodeCoverage.cmake") if(NOT EXISTS ${COVERAGE_CMAKE}) - set(COVERAGE_URL - "https://raw.githubusercontent.com/bilke/cmake-modules/master/CodeCoverage.cmake" - ) + set(COVERAGE_URL "https://raw.githubusercontent.com/bilke/cmake-modules/master/CodeCoverage.cmake") file(DOWNLOAD ${COVERAGE_URL} ${COVERAGE_CMAKE}) endif() include(${COVERAGE_CMAKE}) function(setup_coverage TARGET) - target_compile_options(${TARGET} PRIVATE -g -O0 -fprofile-arcs - -ftest-coverage) + target_compile_options(${TARGET} PRIVATE -g -O0 -fprofile-arcs -ftest-coverage) target_link_libraries(${TARGET} PRIVATE gcov) endfunction() diff --git a/conan-example/main.cpp b/conan-example/main.cpp deleted file mode 100644 index 3dc6420..0000000 --- a/conan-example/main.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include"jwt-cpp/jwt.h" -#include -#include - - -int main() { - - std::string token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE2MTAwMjMxNzcsImV4cCI6MTY0MTU1OTE3NywiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5hbWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IEFkbWluaXN0cmF0b3IiXX0.5EOfHnBmpdPvRHAuVDttgJQvbFuGEF7fC4uBSXAGg6c"; - - auto decoded = jwt::decode(token); - - for(auto& e : decoded.get_payload_claims()) - std::cout << e.first << " = " << e.second << std::endl; - -} \ No newline at end of file diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index 77c5700..0e06b03 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -2,11 +2,11 @@ cmake_minimum_required(VERSION 3.8) project(jwt-cpp-examples) if(NOT TARGET jwt-cpp) - find_package(jwt-cpp CONFIG REQUIRED) + find_package(jwt-cpp CONFIG REQUIRED) endif() if(JWT_DISABLE_PICOJSON) - message(FATAL_ERROR "examples require picojson to be available!") + message(FATAL_ERROR "examples require picojson to be available!") endif() add_executable(print-claims print-claims.cpp) diff --git a/conan-example/CMakeLists.txt b/example/conan/CMakeLists.txt similarity index 68% rename from conan-example/CMakeLists.txt rename to example/conan/CMakeLists.txt index 0dcc350..7bd897c 100644 --- a/conan-example/CMakeLists.txt +++ b/example/conan/CMakeLists.txt @@ -1,7 +1,8 @@ cmake_minimum_required(VERSION 3.8) - project(conan-example) -include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) -conan_basic_setup() + +include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) +conan_basic_setup() + add_executable(${PROJECT_NAME} main.cpp) target_link_libraries(${PROJECT_NAME} ${CONAN_LIBS}) diff --git a/conan-example/README.md b/example/conan/README.md similarity index 85% rename from conan-example/README.md rename to example/conan/README.md index 3f985f5..8032ffd 100644 --- a/conan-example/README.md +++ b/example/conan/README.md @@ -1,18 +1,17 @@ -Conan example - +# Conan example In the current directory on Linux environment -``` + +```sh mkdir build && cd build conan install .. && cmake .. cmake --build . ``` + run executable -``` -./bin/conan-example -``` -the output: -``` + +```sh +$ ./bin/conan-example sub = "jrocket@example.com" iss = "Online JWT Builder" exp = 1641559177 @@ -22,4 +21,4 @@ Role = ["Manager","Project Administrator"] iat = 1610023177 GivenName = "Johnny" Email = "jrocket@example.com" -``` \ No newline at end of file +``` diff --git a/conan-example/conanfile.txt b/example/conan/conanfile.txt similarity index 86% rename from conan-example/conanfile.txt rename to example/conan/conanfile.txt index 335324e..e7a29ff 100644 --- a/conan-example/conanfile.txt +++ b/example/conan/conanfile.txt @@ -2,4 +2,4 @@ jwt-cpp/0.4.0 [generators] -cmake \ No newline at end of file +cmake diff --git a/example/conan/main.cpp b/example/conan/main.cpp new file mode 100644 index 0000000..2773b30 --- /dev/null +++ b/example/conan/main.cpp @@ -0,0 +1,17 @@ +#include "jwt-cpp/jwt.h" +#include +#include + +int main() { + + std::string token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9." + "eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE2MTAwMjMxNzcsImV4cCI6MTY0MTU1OTE3NywiYXVkIjoid3" + "d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsIkdpdmVuTmFtZSI6IkpvaG5ueSIsIlN1cm5h" + "bWUiOiJSb2NrZXQiLCJFbWFpbCI6Impyb2NrZXRAZXhhbXBsZS5jb20iLCJSb2xlIjpbIk1hbmFnZXIiLCJQcm9qZWN0IE" + "FkbWluaXN0cmF0b3IiXX0.5EOfHnBmpdPvRHAuVDttgJQvbFuGEF7fC4uBSXAGg6c"; + + auto decoded = jwt::decode(token); + + for (auto& e : decoded.get_payload_claims()) + std::cout << e.first << " = " << e.second << std::endl; +} diff --git a/example/print-claims.cpp b/example/print-claims.cpp index 09522ca..60cfefe 100644 --- a/example/print-claims.cpp +++ b/example/print-claims.cpp @@ -1,10 +1,11 @@ -#include #include +#include int main(int argc, const char** argv) { - std::string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE"; + std::string token = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE"; auto decoded = jwt::decode(token); - for(auto& e : decoded.get_payload_claims()) + for (auto& e : decoded.get_payload_claims()) std::cout << e.first << " = " << e.second << std::endl; } diff --git a/example/private-claims.cpp b/example/private-claims.cpp index ee5ff2c..2809476 100644 --- a/example/private-claims.cpp +++ b/example/private-claims.cpp @@ -8,152 +8,140 @@ using sec = std::chrono::seconds; using min = std::chrono::minutes; std::string make_pico_token() { - jwt::claim from_raw_json; - std::istringstream iss{R"##({"api":{"array":[1,2,3],"null":null}})##"}; - iss >> from_raw_json; + jwt::claim from_raw_json; + std::istringstream iss{R"##({"api":{"array":[1,2,3],"null":null}})##"}; + iss >> from_raw_json; - jwt::claim::set_t list{"once", "twice"}; + jwt::claim::set_t list{"once", "twice"}; - std::vector big_numbers{727663072ull, 770979831ull, 427239169ull, - 525936436ull}; + std::vector big_numbers{727663072ull, 770979831ull, 427239169ull, 525936436ull}; - const auto time = jwt::date::clock::now(); + const auto time = jwt::date::clock::now(); - return jwt::create() - .set_type("JWT") - .set_issuer("auth.mydomain.io") - .set_audience("mydomain.io") - .set_issued_at(time) - .set_not_before(time + sec{15}) - .set_expires_at(time + sec{15} + min{2}) - .set_payload_claim("boolean", picojson::value(true)) - .set_payload_claim("integer", picojson::value(int64_t{12345})) - .set_payload_claim("precision", picojson::value(12.345)) - .set_payload_claim("strings", jwt::claim(list)) - .set_payload_claim("array", - jwt::claim(big_numbers.begin(), big_numbers.end())) - .set_payload_claim("object", from_raw_json) - .sign(jwt::algorithm::none{}); + return jwt::create() + .set_type("JWT") + .set_issuer("auth.mydomain.io") + .set_audience("mydomain.io") + .set_issued_at(time) + .set_not_before(time + sec{15}) + .set_expires_at(time + sec{15} + min{2}) + .set_payload_claim("boolean", picojson::value(true)) + .set_payload_claim("integer", picojson::value(int64_t{12345})) + .set_payload_claim("precision", picojson::value(12.345)) + .set_payload_claim("strings", jwt::claim(list)) + .set_payload_claim("array", jwt::claim(big_numbers.begin(), big_numbers.end())) + .set_payload_claim("object", from_raw_json) + .sign(jwt::algorithm::none{}); } std::string make_nlohmann_token() { - struct nlohmann_traits { - using json = nlohmann::json; - using value_type = json; - using object_type = json::object_t; - using array_type = json::array_t; - using string_type = std::string; - using number_type = json::number_float_t; - using integer_type = json::number_integer_t; - using boolean_type = json::boolean_t; + struct nlohmann_traits { + using json = nlohmann::json; + using value_type = json; + using object_type = json::object_t; + using array_type = json::array_t; + using string_type = std::string; + using number_type = json::number_float_t; + using integer_type = json::number_integer_t; + using boolean_type = json::boolean_t; - static jwt::json::type get_type(const json &val) { - using jwt::json::type; + static jwt::json::type get_type(const json& val) { + using jwt::json::type; - if (val.type() == json::value_t::boolean) - return type::boolean; - else if (val.type() == json::value_t::number_integer) - return type::integer; - else if (val.type() == json::value_t::number_unsigned) // nlohmann internally tracks two types of integers - return type::integer; - else if (val.type() == json::value_t::number_float) - return type::number; - else if (val.type() == json::value_t::string) - return type::string; - else if (val.type() == json::value_t::array) - return type::array; - else if (val.type() == json::value_t::object) - return type::object; - else - throw std::logic_error("invalid type"); - } + if (val.type() == json::value_t::boolean) + return type::boolean; + else if (val.type() == json::value_t::number_integer) + return type::integer; + else if (val.type() == json::value_t::number_unsigned) // nlohmann internally tracks two types of integers + return type::integer; + else if (val.type() == json::value_t::number_float) + return type::number; + else if (val.type() == json::value_t::string) + return type::string; + else if (val.type() == json::value_t::array) + return type::array; + else if (val.type() == json::value_t::object) + return type::object; + else + throw std::logic_error("invalid type"); + } - static json::object_t as_object(const json &val) { - if (val.type() != json::value_t::object) - throw std::bad_cast(); - return val.get(); - } + static json::object_t as_object(const json& val) { + if (val.type() != json::value_t::object) throw std::bad_cast(); + return val.get(); + } - static std::string as_string(const json &val) { - if (val.type() != json::value_t::string) - throw std::bad_cast(); - return val.get(); - } + static std::string as_string(const json& val) { + if (val.type() != json::value_t::string) throw std::bad_cast(); + return val.get(); + } - static json::array_t as_array(const json &val) { - if (val.type() != json::value_t::array) - throw std::bad_cast(); - return val.get(); - } + static json::array_t as_array(const json& val) { + if (val.type() != json::value_t::array) throw std::bad_cast(); + return val.get(); + } - static int64_t as_int(const json &val) { - switch(val.type()) - { - case json::value_t::number_integer: - case json::value_t::number_unsigned: - return val.get(); - default: - throw std::bad_cast(); - } - } + static int64_t as_int(const json& val) { + switch (val.type()) { + case json::value_t::number_integer: + case json::value_t::number_unsigned: return val.get(); + default: throw std::bad_cast(); + } + } - static bool as_bool(const json &val) { - if (val.type() != json::value_t::boolean) - throw std::bad_cast(); - return val.get(); - } + static bool as_bool(const json& val) { + if (val.type() != json::value_t::boolean) throw std::bad_cast(); + return val.get(); + } - static double as_number(const json &val) { - if (val.type() != json::value_t::number_float) - throw std::bad_cast(); - return val.get(); - } + static double as_number(const json& val) { + if (val.type() != json::value_t::number_float) throw std::bad_cast(); + return val.get(); + } - static bool parse(json &val, std::string str) { - val = json::parse(str.begin(), str.end()); - return true; - } + static bool parse(json& val, std::string str) { + val = json::parse(str.begin(), str.end()); + return true; + } - static std::string serialize(const json &val) { return val.dump(); } - }; + static std::string serialize(const json& val) { return val.dump(); } + }; - using claim = jwt::basic_claim; + using claim = jwt::basic_claim; - claim from_raw_json; - std::istringstream iss{R"##({"api":{"array":[1,2,3],"null":null}})##"}; - iss >> from_raw_json; + claim from_raw_json; + std::istringstream iss{R"##({"api":{"array":[1,2,3],"null":null}})##"}; + iss >> from_raw_json; - claim::set_t list{"once", "twice"}; + claim::set_t list{"once", "twice"}; - std::vector big_numbers{727663072ull, 770979831ull, 427239169ull, - 525936436ull}; + std::vector big_numbers{727663072ull, 770979831ull, 427239169ull, 525936436ull}; - const auto time = jwt::date::clock::now(); + const auto time = jwt::date::clock::now(); - return jwt::create() - .set_type("JWT") - .set_issuer("auth.mydomain.io") - .set_audience("mydomain.io") - .set_issued_at(time) - .set_not_before(time + sec{15}) - .set_expires_at(time + sec{15} + min{2}) - .set_payload_claim("boolean", true) - .set_payload_claim("integer", 12345) - .set_payload_claim("precision", 12.345) - .set_payload_claim("strings", list) - .set_payload_claim("array", {big_numbers.begin(), big_numbers.end()}) - .set_payload_claim("object", from_raw_json) - .sign(jwt::algorithm::none{}); + return jwt::create() + .set_type("JWT") + .set_issuer("auth.mydomain.io") + .set_audience("mydomain.io") + .set_issued_at(time) + .set_not_before(time + sec{15}) + .set_expires_at(time + sec{15} + min{2}) + .set_payload_claim("boolean", true) + .set_payload_claim("integer", 12345) + .set_payload_claim("precision", 12.345) + .set_payload_claim("strings", list) + .set_payload_claim("array", {big_numbers.begin(), big_numbers.end()}) + .set_payload_claim("object", from_raw_json) + .sign(jwt::algorithm::none{}); } -int main(int argc, const char **argv) { - const auto token = make_pico_token(); - auto decoded = jwt::decode(token); +int main(int argc, const char** argv) { + const auto token = make_pico_token(); + auto decoded = jwt::decode(token); - for (auto &e : decoded.get_payload_claims()) - std::cout << e.first << " = " << e.second << std::endl; + for (auto& e : decoded.get_payload_claims()) + std::cout << e.first << " = " << e.second << std::endl; - const auto api_array = - decoded.get_payload_claims()["object"].to_json().get("api").get("array"); - std::cout << "api array = " << api_array << std::endl; + const auto api_array = decoded.get_payload_claims()["object"].to_json().get("api").get("array"); + std::cout << "api array = " << api_array << std::endl; } diff --git a/example/rsa-create.cpp b/example/rsa-create.cpp index 0c25396..c9f39ab 100644 --- a/example/rsa-create.cpp +++ b/example/rsa-create.cpp @@ -1,8 +1,8 @@ #include #include -int main(int argc, const char **argv) { - std::string rsa_priv_key = R"(-----BEGIN PRIVATE KEY----- +int main(int argc, const char** argv) { + std::string rsa_priv_key = R"(-----BEGIN PRIVATE KEY----- MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC4ZtdaIrd1BPIJ tfnF0TjIK5inQAXZ3XlCrUlJdP+XHwIRxdv1FsN12XyMYO/6ymLmo9ryoQeIrsXB XYqlET3zfAY+diwCb0HEsVvhisthwMU4gZQu6TYW2s9LnXZB5rVtcBK69hcSlA2k @@ -30,7 +30,7 @@ RultUEe2C0jYMDQx+JYxbPmtcopvZQrFEur3WKVuLy5UAy7EBvwMnZwIG7OOohJb vkSpADK6VPn9lbqq7O8cTedEHttm6otmLt8ZyEl3hZMaL3hbuRj6ysjmoFKx6CrX rK0/Ikt5ybqUzKCMJZg2VKGTxg== -----END PRIVATE KEY-----)"; - std::string rsa_pub_key = R"(-----BEGIN PUBLIC KEY----- + std::string rsa_pub_key = R"(-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuGbXWiK3dQTyCbX5xdE4 yCuYp0AF2d15Qq1JSXT/lx8CEcXb9RbDddl8jGDv+spi5qPa8qEHiK7FwV2KpRE9 83wGPnYsAm9BxLFb4YrLYcDFOIGULuk2FtrPS512Qea1bXASuvYXEpQNpGbnTGVs @@ -40,15 +40,14 @@ AziMCxS+VrRPDM+zfvpIJg3JljAh3PJHDiLu902v9w+Iplu1WyoB2aPfitxEhRN0 YwIDAQAB -----END PUBLIC KEY-----)"; - auto token = - jwt::create() - .set_issuer("auth0") - .set_type("JWT") - .set_id("rsa-create-example") - .set_issued_at(std::chrono::system_clock::now()) - .set_expires_at(std::chrono::system_clock::now() + std::chrono::seconds{36000}) - .set_payload_claim("sample", jwt::claim(std::string{"test"})) - .sign(jwt::algorithm::rs256(rsa_pub_key, rsa_priv_key, "", "")); + auto token = jwt::create() + .set_issuer("auth0") + .set_type("JWT") + .set_id("rsa-create-example") + .set_issued_at(std::chrono::system_clock::now()) + .set_expires_at(std::chrono::system_clock::now() + std::chrono::seconds{36000}) + .set_payload_claim("sample", jwt::claim(std::string{"test"})) + .sign(jwt::algorithm::rs256(rsa_pub_key, rsa_priv_key, "", "")); - std::cout << "token:\n" << token << std::endl; + std::cout << "token:\n" << token << std::endl; } diff --git a/example/rsa-verify.cpp b/example/rsa-verify.cpp index 51aa716..5fe65e8 100644 --- a/example/rsa-verify.cpp +++ b/example/rsa-verify.cpp @@ -1,8 +1,8 @@ #include #include -int main(int argc, const char **argv) { - std::string rsa_priv_key = R"(-----BEGIN PRIVATE KEY----- +int main(int argc, const char** argv) { + std::string rsa_priv_key = R"(-----BEGIN PRIVATE KEY----- MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC4ZtdaIrd1BPIJ tfnF0TjIK5inQAXZ3XlCrUlJdP+XHwIRxdv1FsN12XyMYO/6ymLmo9ryoQeIrsXB XYqlET3zfAY+diwCb0HEsVvhisthwMU4gZQu6TYW2s9LnXZB5rVtcBK69hcSlA2k @@ -30,7 +30,7 @@ RultUEe2C0jYMDQx+JYxbPmtcopvZQrFEur3WKVuLy5UAy7EBvwMnZwIG7OOohJb vkSpADK6VPn9lbqq7O8cTedEHttm6otmLt8ZyEl3hZMaL3hbuRj6ysjmoFKx6CrX rK0/Ikt5ybqUzKCMJZg2VKGTxg== -----END PRIVATE KEY-----)"; - std::string rsa_pub_key = R"(-----BEGIN PUBLIC KEY----- + std::string rsa_pub_key = R"(-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuGbXWiK3dQTyCbX5xdE4 yCuYp0AF2d15Qq1JSXT/lx8CEcXb9RbDddl8jGDv+spi5qPa8qEHiK7FwV2KpRE9 83wGPnYsAm9BxLFb4YrLYcDFOIGULuk2FtrPS512Qea1bXASuvYXEpQNpGbnTGVs @@ -40,27 +40,24 @@ AziMCxS+VrRPDM+zfvpIJg3JljAh3PJHDiLu902v9w+Iplu1WyoB2aPfitxEhRN0 YwIDAQAB -----END PUBLIC KEY-----)"; - std::string token = - "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9." - "VA2i1ui1cnoD6I3wnji1WAVCf29EekysvevGrT2GXqK1dDMc8" - "HAZCTQxa1Q8NppnpYV-hlqxh-X3Bb0JOePTGzjynpNZoJh2aHZD-" - "GKpZt7OO1Zp8AFWPZ3p8Cahq8536fD8RiBES9jRsvChZvOqA7gMcFc4" - "YD0iZhNIcI7a654u5yPYyTlf5kjR97prCf_OXWRn-bYY74zna4p_bP9oWCL4BkaoRcMxi-" - "IR7kmVcCnvbYqyIrKloXP2qPO442RBGqU7Ov9" - "sGQxiVqtRHKXZR9RbfvjrErY1KGiCp9M5i2bsUHadZEY44FE2jiOmx-" - "uc2z5c05CCXqVSpfCjWbh9gQ"; + std::string token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9." + "VA2i1ui1cnoD6I3wnji1WAVCf29EekysvevGrT2GXqK1dDMc8" + "HAZCTQxa1Q8NppnpYV-hlqxh-X3Bb0JOePTGzjynpNZoJh2aHZD-" + "GKpZt7OO1Zp8AFWPZ3p8Cahq8536fD8RiBES9jRsvChZvOqA7gMcFc4" + "YD0iZhNIcI7a654u5yPYyTlf5kjR97prCf_OXWRn-bYY74zna4p_bP9oWCL4BkaoRcMxi-" + "IR7kmVcCnvbYqyIrKloXP2qPO442RBGqU7Ov9" + "sGQxiVqtRHKXZR9RbfvjrErY1KGiCp9M5i2bsUHadZEY44FE2jiOmx-" + "uc2z5c05CCXqVSpfCjWbh9gQ"; - auto verify = jwt::verify() - .allow_algorithm(jwt::algorithm::rs256( - rsa_pub_key, rsa_priv_key, "", "")) - .with_issuer("auth0"); + auto verify = + jwt::verify().allow_algorithm(jwt::algorithm::rs256(rsa_pub_key, rsa_priv_key, "", "")).with_issuer("auth0"); - auto decoded = jwt::decode(token); + auto decoded = jwt::decode(token); - verify.verify(decoded); + verify.verify(decoded); - for (auto &e : decoded.get_header_claims()) - std::cout << e.first << " = " << e.second.to_json() << std::endl; - for (auto &e : decoded.get_payload_claims()) - std::cout << e.first << " = " << e.second.to_json() << std::endl; + for (auto& e : decoded.get_header_claims()) + std::cout << e.first << " = " << e.second.to_json() << std::endl; + for (auto& e : decoded.get_payload_claims()) + std::cout << e.first << " = " << e.second.to_json() << std::endl; } diff --git a/include/jwt-cpp/base.h b/include/jwt-cpp/base.h index 4ea35ba..c447113 100644 --- a/include/jwt-cpp/base.h +++ b/include/jwt-cpp/base.h @@ -18,49 +18,47 @@ namespace jwt { /** * \brief character maps when encoding and decoding - */ + */ namespace alphabet { /** * \brief valid list of characted when working with [Base64](https://tools.ietf.org/html/rfc3548) - */ + */ struct base64 { static const std::array& data() { - static constexpr std::array data { - {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', - 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', - 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'} - }; + static constexpr std::array data{ + {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}}; return data; } static const std::string& fill() { - static std::string fill{ "=" }; + static std::string fill{"="}; return fill; } }; /** * \brief valid list of characted when working with [Base64URL](https://tools.ietf.org/html/rfc4648) - */ + */ struct base64url { static const std::array& data() { - static constexpr std::array data { - {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', - 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', - 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', - 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'} - }; + static constexpr std::array data{ + {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'}}; return data; } static const std::string& fill() { - static std::string fill{ "%3d" }; + static std::string fill{"%3d"}; return fill; } }; - } // namespace alphabet + } // namespace alphabet /** * \brief Alphabet generic methods for working with encoding/decoding the base64 family - */ + */ class base { public: template @@ -81,7 +79,8 @@ namespace jwt { } private: - static std::string encode(const std::string& bin, const std::array& alphabet, const std::string& fill) { + static std::string encode(const std::string& bin, const std::array& alphabet, + const std::string& fill) { size_t size = bin.size(); std::string res; @@ -100,8 +99,7 @@ namespace jwt { res += alphabet[(triple >> 0 * 6) & 0x3F]; } - if (fast_size == size) - return res; + if (fast_size == size) return res; size_t mod = size % 3; @@ -124,14 +122,14 @@ namespace jwt { res += alphabet[(triple >> 1 * 6) & 0x3F]; res += fill; break; - default: - break; + default: break; } return res; } - static std::string decode(const std::string& base, const std::array& alphabet, const std::string& fill) { + static std::string decode(const std::string& base, const std::array& alphabet, + const std::string& fill) { size_t size = base.size(); size_t fill_cnt = 0; @@ -139,14 +137,12 @@ namespace jwt { if (base.substr(size - fill.size(), fill.size()) == fill) { fill_cnt++; size -= fill.size(); - if(fill_cnt > 2) - throw std::runtime_error("Invalid input"); - } - else break; + if (fill_cnt > 2) throw std::runtime_error("Invalid input"); + } else + break; } - if ((size + fill_cnt) % 4 != 0) - throw std::runtime_error("Invalid input"); + if ((size + fill_cnt) % 4 != 0) throw std::runtime_error("Invalid input"); size_t out_size = size / 4 * 3; std::string res; @@ -154,8 +150,7 @@ namespace jwt { auto get_sextet = [&](size_t offset) { for (size_t i = 0; i < alphabet.size(); i++) { - if (alphabet[i] == base[offset]) - return static_cast(i); + if (alphabet[i] == base[offset]) return static_cast(i); } throw std::runtime_error("Invalid input"); }; @@ -167,21 +162,16 @@ namespace jwt { uint32_t sextet_c = get_sextet(i++); uint32_t sextet_d = get_sextet(i++); - uint32_t triple = (sextet_a << 3 * 6) - + (sextet_b << 2 * 6) - + (sextet_c << 1 * 6) - + (sextet_d << 0 * 6); + uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6); res += static_cast((triple >> 2 * 8) & 0xFFU); res += static_cast((triple >> 1 * 8) & 0xFFU); res += static_cast((triple >> 0 * 8) & 0xFFU); } - if (fill_cnt == 0) - return res; + if (fill_cnt == 0) return res; - uint32_t triple = (get_sextet(fast_size) << 3 * 6) - + (get_sextet(fast_size + 1) << 2 * 6); + uint32_t triple = (get_sextet(fast_size) << 3 * 6) + (get_sextet(fast_size + 1) << 2 * 6); switch (fill_cnt) { case 1: @@ -189,30 +179,20 @@ namespace jwt { res += static_cast((triple >> 2 * 8) & 0xFFU); res += static_cast((triple >> 1 * 8) & 0xFFU); break; - case 2: - res += static_cast((triple >> 2 * 8) & 0xFFU); - break; - default: - break; + case 2: res += static_cast((triple >> 2 * 8) & 0xFFU); break; + default: break; } return res; } - + static std::string pad(const std::string& base, const std::string& fill) { std::string padding; switch (base.size() % 4) { - case 1: - padding += fill; - JWT_FALLTHROUGH; - case 2: - padding += fill; - JWT_FALLTHROUGH; - case 3: - padding += fill; - JWT_FALLTHROUGH; - default: - break; + case 1: padding += fill; JWT_FALLTHROUGH; + case 2: padding += fill; JWT_FALLTHROUGH; + case 3: padding += fill; JWT_FALLTHROUGH; + default: break; } return base + padding; @@ -223,6 +203,6 @@ namespace jwt { return base.substr(0, pos); } }; -} // namespace jwt +} // namespace jwt #endif diff --git a/include/jwt-cpp/jwt.h b/include/jwt-cpp/jwt.h index 4b95606..64b6c86 100644 --- a/include/jwt-cpp/jwt.h +++ b/include/jwt-cpp/jwt.h @@ -18,14 +18,14 @@ #include #include +#include #include #include #include +#include +#include #include #include -#include -#include -#include #if __cplusplus >= 201402L #ifdef __has_include @@ -35,12 +35,12 @@ #endif #endif -//If openssl version less than 1.1 +// If openssl version less than 1.1 #if OPENSSL_VERSION_NUMBER < 0x10100000L #define OPENSSL10 #endif -//If openssl version less than 1.1.1 +// If openssl version less than 1.1.1 #if OPENSSL_VERSION_NUMBER < 0x10101000L #define OPENSSL110 #endif @@ -102,12 +102,11 @@ namespace jwt { * \brief Error category for RSA errors */ inline std::error_category& rsa_error_category() { - class rsa_error_cat : public std::error_category - { + class rsa_error_cat : public std::error_category { public: const char* name() const noexcept override { return "rsa_error"; }; std::string message(int ev) const override { - switch(static_cast(ev)) { + switch (static_cast(ev)) { case rsa_error::ok: return "no error"; case rsa_error::cert_load_failed: return "error loading cert into memory"; case rsa_error::get_key_failed: return "error getting key from certificate"; @@ -126,9 +125,7 @@ namespace jwt { return cat; } - inline std::error_code make_error_code(rsa_error e) { - return {static_cast(e), rsa_error_category()}; - } + inline std::error_code make_error_code(rsa_error e) { return {static_cast(e), rsa_error_category()}; } /** * \brief Errors related to processing of RSA signatures */ @@ -145,17 +142,17 @@ namespace jwt { * \brief Error category for ECDSA errors */ inline std::error_category& ecdsa_error_category() { - class ecdsa_error_cat : public std::error_category - { + class ecdsa_error_cat : public std::error_category { public: const char* name() const noexcept override { return "ecdsa_error"; }; std::string message(int ev) const override { - switch(static_cast(ev)) { + switch (static_cast(ev)) { case ecdsa_error::ok: return "no error"; case ecdsa_error::load_key_bio_write: return "failed to load key: bio write failed"; case ecdsa_error::load_key_bio_read: return "failed to load key: bio read failed"; case ecdsa_error::create_mem_bio_failed: return "failed to create memory bio"; - case ecdsa_error::no_key_provided: return "at least one of public or private key need to be present"; + case ecdsa_error::no_key_provided: + return "at least one of public or private key need to be present"; case ecdsa_error::invalid_key_size: return "invalid key size"; case ecdsa_error::invalid_key: return "invalid key"; default: return "unknown ECDSA error"; @@ -166,9 +163,7 @@ namespace jwt { return cat; } - inline std::error_code make_error_code(ecdsa_error e) { - return {static_cast(e), ecdsa_error_category()}; - } + inline std::error_code make_error_code(ecdsa_error e) { return {static_cast(e), ecdsa_error_category()}; } /** * \brief Errors related to verification of signatures @@ -186,19 +181,23 @@ namespace jwt { * \brief Error category for verification errors */ inline std::error_category& signature_verification_error_category() { - class verification_error_cat : public std::error_category - { + class verification_error_cat : public std::error_category { public: const char* name() const noexcept override { return "signature_verification_error"; }; std::string message(int ev) const override { - switch(static_cast(ev)) { + switch (static_cast(ev)) { case signature_verification_error::ok: return "no error"; case signature_verification_error::invalid_signature: return "invalid signature"; - case signature_verification_error::create_context_failed: return "failed to verify signature: could not create context"; - case signature_verification_error::verifyinit_failed: return "failed to verify signature: VerifyInit failed"; - case signature_verification_error::verifyupdate_failed: return "failed to verify signature: VerifyUpdate failed"; - case signature_verification_error::verifyfinal_failed: return "failed to verify signature: VerifyFinal failed"; - case signature_verification_error::get_key_failed: return "failed to verify signature: Could not get key"; + case signature_verification_error::create_context_failed: + return "failed to verify signature: could not create context"; + case signature_verification_error::verifyinit_failed: + return "failed to verify signature: VerifyInit failed"; + case signature_verification_error::verifyupdate_failed: + return "failed to verify signature: VerifyUpdate failed"; + case signature_verification_error::verifyfinal_failed: + return "failed to verify signature: VerifyFinal failed"; + case signature_verification_error::get_key_failed: + return "failed to verify signature: Could not get key"; default: return "unknown signature verification error"; } } @@ -233,25 +232,34 @@ namespace jwt { * \brief Error category for signature generation errors */ inline std::error_category& signature_generation_error_category() { - class signature_generation_error_cat : public std::error_category - { + class signature_generation_error_cat : public std::error_category { public: const char* name() const noexcept override { return "signature_generation_error"; }; std::string message(int ev) const override { - switch(static_cast(ev)) { + switch (static_cast(ev)) { case signature_generation_error::ok: return "no error"; case signature_generation_error::hmac_failed: return "hmac failed"; - case signature_generation_error::create_context_failed: return "failed to create signature: could not create context"; - case signature_generation_error::signinit_failed: return "failed to create signature: SignInit failed"; - case signature_generation_error::signupdate_failed: return "failed to create signature: SignUpdate failed"; - case signature_generation_error::signfinal_failed: return "failed to create signature: SignFinal failed"; + case signature_generation_error::create_context_failed: + return "failed to create signature: could not create context"; + case signature_generation_error::signinit_failed: + return "failed to create signature: SignInit failed"; + case signature_generation_error::signupdate_failed: + return "failed to create signature: SignUpdate failed"; + case signature_generation_error::signfinal_failed: + return "failed to create signature: SignFinal failed"; case signature_generation_error::ecdsa_do_sign_failed: return "failed to generate ecdsa signature"; - case signature_generation_error::digestinit_failed: return "failed to create signature: DigestInit failed"; - case signature_generation_error::digestupdate_failed: return "failed to create signature: DigestUpdate failed"; - case signature_generation_error::digestfinal_failed: return "failed to create signature: DigestFinal failed"; - case signature_generation_error::rsa_padding_failed: return "failed to create signature: RSA_padding_add_PKCS1_PSS_mgf1 failed"; - case signature_generation_error::rsa_private_encrypt_failed: return "failed to create signature: RSA_private_encrypt failed"; - case signature_generation_error::get_key_failed: return "failed to generate signature: Could not get key"; + case signature_generation_error::digestinit_failed: + return "failed to create signature: DigestInit failed"; + case signature_generation_error::digestupdate_failed: + return "failed to create signature: DigestUpdate failed"; + case signature_generation_error::digestfinal_failed: + return "failed to create signature: DigestFinal failed"; + case signature_generation_error::rsa_padding_failed: + return "failed to create signature: RSA_padding_add_PKCS1_PSS_mgf1 failed"; + case signature_generation_error::rsa_private_encrypt_failed: + return "failed to create signature: RSA_private_encrypt failed"; + case signature_generation_error::get_key_failed: + return "failed to generate signature: Could not get key"; default: return "unknown signature generation error"; } } @@ -280,19 +288,21 @@ namespace jwt { * \brief Error category for token verification errors */ inline std::error_category& token_verification_error_category() { - class token_verification_error_cat : public std::error_category - { + class token_verification_error_cat : public std::error_category { public: const char* name() const noexcept override { return "token_verification_error"; }; std::string message(int ev) const override { - switch(static_cast(ev)) { + switch (static_cast(ev)) { case token_verification_error::ok: return "no error"; case token_verification_error::wrong_algorithm: return "wrong algorithm"; case token_verification_error::missing_claim: return "decoded JWT is missing required claim(s)"; - case token_verification_error::claim_type_missmatch: return "claim type does not match expected type"; - case token_verification_error::claim_value_missmatch: return "claim value does not match expected value"; + case token_verification_error::claim_type_missmatch: + return "claim type does not match expected type"; + case token_verification_error::claim_value_missmatch: + return "claim value does not match expected value"; case token_verification_error::token_expired: return "token expired"; - case token_verification_error::audience_missmatch: return "token doesn't contain the required audience"; + case token_verification_error::audience_missmatch: + return "token doesn't contain the required audience"; default: return "unknown token verification error"; } } @@ -306,41 +316,37 @@ namespace jwt { } inline void throw_if_error(std::error_code ec) { - if(ec) { - if(ec.category() == rsa_error_category()) - throw rsa_exception(ec); - if(ec.category() == ecdsa_error_category()) - throw ecdsa_exception(ec); - if(ec.category() == signature_verification_error_category()) + if (ec) { + if (ec.category() == rsa_error_category()) throw rsa_exception(ec); + if (ec.category() == ecdsa_error_category()) throw ecdsa_exception(ec); + if (ec.category() == signature_verification_error_category()) throw signature_verification_exception(ec); - if(ec.category() == signature_generation_error_category()) - throw signature_generation_exception(ec); - if(ec.category() == token_verification_error_category()) - throw token_verification_exception(ec); + if (ec.category() == signature_generation_error_category()) throw signature_generation_exception(ec); + if (ec.category() == token_verification_error_category()) throw token_verification_exception(ec); } } - } + } // namespace error + // FIXME: Remove // Keep backward compat at least for a couple of revisions - using error::signature_verification_exception; - using error::signature_generation_exception; - using error::rsa_exception; using error::ecdsa_exception; + using error::rsa_exception; + using error::signature_generation_exception; + using error::signature_verification_exception; using error::token_verification_exception; -} -namespace std -{ - template <> +} // namespace jwt +namespace std { + template<> struct is_error_code_enum : true_type {}; - template <> + template<> struct is_error_code_enum : true_type {}; - template <> + template<> struct is_error_code_enum : true_type {}; - template <> + template<> struct is_error_code_enum : true_type {}; - template <> + template<> struct is_error_code_enum : true_type {}; -} +} // namespace std namespace jwt { /** * \brief A collection for working with certificates @@ -357,37 +363,40 @@ namespace jwt { * \param pw Password used to decrypt certificate (leave empty if not encrypted) * \param ec error_code for error_detection (gets cleared if no error occures) */ - inline - std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw, std::error_code& ec) { + inline std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw, + std::error_code& ec) { ec.clear(); #if OPENSSL_VERSION_NUMBER <= 0x10100003L - std::unique_ptr certbio(BIO_new_mem_buf(const_cast(certstr.data()), static_cast(certstr.size())), BIO_free_all); + std::unique_ptr certbio( + BIO_new_mem_buf(const_cast(certstr.data()), static_cast(certstr.size())), BIO_free_all); #else - std::unique_ptr certbio(BIO_new_mem_buf(certstr.data(), static_cast(certstr.size())), BIO_free_all); + std::unique_ptr certbio( + BIO_new_mem_buf(certstr.data(), static_cast(certstr.size())), BIO_free_all); #endif std::unique_ptr keybio(BIO_new(BIO_s_mem()), BIO_free_all); - if(!certbio || !keybio) { + if (!certbio || !keybio) { ec = error::rsa_error::create_mem_bio_failed; return {}; } - std::unique_ptr cert(PEM_read_bio_X509(certbio.get(), nullptr, nullptr, const_cast(pw.c_str())), X509_free); + std::unique_ptr cert( + PEM_read_bio_X509(certbio.get(), nullptr, nullptr, const_cast(pw.c_str())), X509_free); if (!cert) { ec = error::rsa_error::cert_load_failed; return {}; } std::unique_ptr key(X509_get_pubkey(cert.get()), EVP_PKEY_free); - if(!key) { + if (!key) { ec = error::rsa_error::get_key_failed; return {}; } - if(PEM_write_bio_PUBKEY(keybio.get(), key.get()) == 0) { + if (PEM_write_bio_PUBKEY(keybio.get(), key.get()) == 0) { ec = error::rsa_error::write_key_failed; return {}; } char* ptr = nullptr; auto len = BIO_get_mem_data(keybio.get(), &ptr); - if(len <= 0 || ptr == nullptr) { + if (len <= 0 || ptr == nullptr) { ec = error::rsa_error::convert_to_pem_failed; return {}; } @@ -401,8 +410,7 @@ namespace jwt { * \param pw Password used to decrypt certificate (leave empty if not encrypted) * \throw rsa_exception if an error occurred */ - inline - std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw = "") { + inline std::string extract_pubkey_from_cert(const std::string& certstr, const std::string& pw = "") { std::error_code ec; auto res = extract_pubkey_from_cert(certstr, pw, ec); error::throw_if_error(ec); @@ -424,27 +432,27 @@ namespace jwt { * \param ec error_code for error_detection (gets cleared if no error occures) */ template - std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, Decode decode, std::error_code& ec) { + std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, Decode decode, + std::error_code& ec) { ec.clear(); const auto decodedStr = decode(cert_base64_der_str); - auto c_str = reinterpret_cast (decodedStr.c_str()); + auto c_str = reinterpret_cast(decodedStr.c_str()); std::unique_ptr cert(d2i_X509(NULL, &c_str, decodedStr.size()), X509_free); std::unique_ptr certbio(BIO_new(BIO_s_mem()), BIO_free_all); - if(!cert || !certbio) { + if (!cert || !certbio) { ec = error::rsa_error::create_mem_bio_failed; return {}; } - if(!PEM_write_bio_X509(certbio.get(), cert.get())) - { + if (!PEM_write_bio_X509(certbio.get(), cert.get())) { ec = error::rsa_error::write_cert_failed; return {}; } char* ptr = nullptr; const auto len = BIO_get_mem_data(certbio.get(), &ptr); - if(len <= 0 || ptr == nullptr) { + if (len <= 0 || ptr == nullptr) { ec = error::rsa_error::convert_to_pem_failed; return {}; } @@ -483,9 +491,10 @@ namespace jwt { * \param cert_base64_der_str String containing the certificate encoded as base64 DER * \param ec error_code for error_detection (gets cleared if no error occures) */ - inline - std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, std::error_code& ec) { - auto decode = [](const std::string& token){return base::decode(base::pad(token));}; + inline std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str, std::error_code& ec) { + auto decode = [](const std::string& token) { + return base::decode(base::pad(token)); + }; return convert_base64_der_to_pem(cert_base64_der_str, std::move(decode), ec); } @@ -498,8 +507,7 @@ namespace jwt { * \param cert_base64_der_str String containing the certificate encoded as base64 DER * \throw rsa_exception if an error occurred */ - inline - std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str) { + inline std::string convert_base64_der_to_pem(const std::string& cert_base64_der_str) { std::error_code ec; auto res = convert_base64_der_to_pem(cert_base64_der_str, ec); error::throw_if_error(ec); @@ -515,17 +523,17 @@ namespace jwt { * \param pw Password used to decrypt certificate (leave empty if not encrypted) * \param ec error_code for error_detection (gets cleared if no error occures) */ - inline - std::shared_ptr load_public_key_from_string(const std::string& key, const std::string& password, std::error_code& ec) { + inline std::shared_ptr load_public_key_from_string(const std::string& key, + const std::string& password, std::error_code& ec) { ec.clear(); std::unique_ptr pubkey_bio(BIO_new(BIO_s_mem()), BIO_free_all); - if(!pubkey_bio) { + if (!pubkey_bio) { ec = error::rsa_error::create_mem_bio_failed; return nullptr; } - if(key.substr(0, 27) == "-----BEGIN CERTIFICATE-----") { + if (key.substr(0, 27) == "-----BEGIN CERTIFICATE-----") { auto epkey = helper::extract_pubkey_from_cert(key, password, ec); - if(ec) return nullptr; + if (ec) return nullptr; const int len = static_cast(epkey.size()); if (BIO_write(pubkey_bio.get(), epkey.data(), len) != len) { ec = error::rsa_error::load_key_bio_write; @@ -539,7 +547,10 @@ namespace jwt { } } - std::shared_ptr pkey(PEM_read_bio_PUBKEY(pubkey_bio.get(), nullptr, nullptr, (void*)password.data()), EVP_PKEY_free); // NOLINT(google-readability-casting) requires `const_cast` + std::shared_ptr pkey( + PEM_read_bio_PUBKEY(pubkey_bio.get(), nullptr, nullptr, + (void*)password.data()), // NOLINT(google-readability-casting) requires `const_cast` + EVP_PKEY_free); if (!pkey) { ec = error::rsa_error::load_key_bio_read; return nullptr; @@ -556,8 +567,8 @@ namespace jwt { * \param pw Password used to decrypt certificate or key (leave empty if not encrypted) * \throw rsa_exception if an error occurred */ - inline - std::shared_ptr load_public_key_from_string(const std::string& key, const std::string& password = "") { + inline std::shared_ptr load_public_key_from_string(const std::string& key, + const std::string& password = "") { std::error_code ec; auto res = load_public_key_from_string(key, password, ec); error::throw_if_error(ec); @@ -571,10 +582,10 @@ namespace jwt { * \param pw Password used to decrypt key (leave empty if not encrypted) * \param ec error_code for error_detection (gets cleared if no error occures) */ - inline - std::shared_ptr load_private_key_from_string(const std::string& key, const std::string& password, std::error_code& ec) { + inline std::shared_ptr + load_private_key_from_string(const std::string& key, const std::string& password, std::error_code& ec) { std::unique_ptr privkey_bio(BIO_new(BIO_s_mem()), BIO_free_all); - if(!privkey_bio) { + if (!privkey_bio) { ec = error::rsa_error::create_mem_bio_failed; return nullptr; } @@ -583,7 +594,9 @@ namespace jwt { ec = error::rsa_error::load_key_bio_write; return nullptr; } - std::shared_ptr pkey(PEM_read_bio_PrivateKey(privkey_bio.get(), nullptr, nullptr, const_cast(password.c_str())), EVP_PKEY_free); + std::shared_ptr pkey( + PEM_read_bio_PrivateKey(privkey_bio.get(), nullptr, nullptr, const_cast(password.c_str())), + EVP_PKEY_free); if (!pkey) { ec = error::rsa_error::load_key_bio_read; return nullptr; @@ -598,8 +611,8 @@ namespace jwt { * \param pw Password used to decrypt key (leave empty if not encrypted) * \throw rsa_exception if an error occurred */ - inline - std::shared_ptr load_private_key_from_string(const std::string& key, const std::string& password = "") { + inline std::shared_ptr load_private_key_from_string(const std::string& key, + const std::string& password = "") { std::error_code ec; auto res = load_private_key_from_string(key, password, ec); error::throw_if_error(ec); @@ -613,13 +626,15 @@ namespace jwt { */ inline #ifdef OPENSSL10 - static std::string bn2raw(BIGNUM* bn) + static std::string + bn2raw(BIGNUM* bn) #else - static std::string bn2raw(const BIGNUM* bn) + static std::string + bn2raw(const BIGNUM* bn) #endif { std::string res(BN_num_bytes(bn), '\0'); - BN_bn2bin(bn, (unsigned char*)res.data()); // NOLINT(google-readability-casting) requires `const_cast` + BN_bn2bin(bn, (unsigned char*)res.data()); // NOLINT(google-readability-casting) requires `const_cast` return res; } /** @@ -627,19 +642,21 @@ namespace jwt { * \param raw String to convert * \return BIGNUM representation */ - inline - static std::unique_ptr raw2bn(const std::string& raw) { - return std::unique_ptr(BN_bin2bn(reinterpret_cast(raw.data()), static_cast(raw.size()), nullptr), BN_free); + inline static std::unique_ptr raw2bn(const std::string& raw) { + return std::unique_ptr( + BN_bin2bn(reinterpret_cast(raw.data()), static_cast(raw.size()), nullptr), + BN_free); } - } // namespace helper + } // namespace helper /** * \brief Various cryptographic algorithms when working with JWT * * JWT (JSON Web Tokens) signatures are typically used as the payload for a JWS (JSON Web Signature) or - * JWE (JSON Web Encryption). Both of these use various cryptographic as specified by [RFC7518](https://tools.ietf.org/html/rfc7518) - * and are exposed through the a [JOSE Header](https://tools.ietf.org/html/rfc7515#section-4) which - * points to one of the JWA (JSON Web Algorithms)(https://tools.ietf.org/html/rfc7518#section-3.1) + * JWE (JSON Web Encryption). Both of these use various cryptographic as specified by + * [RFC7518](https://tools.ietf.org/html/rfc7518) and are exposed through the a [JOSE + * Header](https://tools.ietf.org/html/rfc7515#section-4) which points to one of the JWA (JSON Web + * Algorithms)(https://tools.ietf.org/html/rfc7518#section-3.1) */ namespace algorithm { /** @@ -664,14 +681,10 @@ namespace jwt { */ void verify(const std::string& /*unused*/, const std::string& signature, std::error_code& ec) const { ec.clear(); - if (!signature.empty()) { - ec = error::signature_verification_error::invalid_signature; - } + if (!signature.empty()) { ec = error::signature_verification_error::invalid_signature; } } /// Get algorithm name - std::string name() const { - return "none"; - } + std::string name() const { return "none"; } }; /** * \brief Base class for HMAC family of algorithms @@ -683,9 +696,8 @@ namespace jwt { * \param md Pointer to hash function * \param name Name of the algorithm */ - hmacsha(std::string key, const EVP_MD*(*md)(), std::string name) - : secret(std::move(key)), md(md), alg_name(std::move(name)) - {} + hmacsha(std::string key, const EVP_MD* (*md)(), std::string name) + : secret(std::move(key)), md(md), alg_name(std::move(name)) {} /** * Sign jwt data * \param data The data to sign @@ -696,7 +708,10 @@ namespace jwt { ec.clear(); std::string res(static_cast(EVP_MAX_MD_SIZE), '\0'); auto len = static_cast(res.size()); - if (HMAC(md(), secret.data(), static_cast(secret.size()), reinterpret_cast(data.data()), static_cast(data.size()), (unsigned char*)res.data(), &len) == nullptr) { // NOLINT(google-readability-casting) requires `const_cast` + if (HMAC(md(), secret.data(), static_cast(secret.size()), + reinterpret_cast(data.data()), static_cast(data.size()), + (unsigned char*)res.data(), // NOLINT(google-readability-casting) requires `const_cast` + &len) == nullptr) { ec = error::signature_generation_error::hmac_failed; return {}; } @@ -712,13 +727,12 @@ namespace jwt { void verify(const std::string& data, const std::string& signature, std::error_code& ec) const { ec.clear(); auto res = sign(data, ec); - if(ec) return; + if (ec) return; + bool matched = true; for (size_t i = 0; i < std::min(res.size(), signature.size()); i++) - if (res[i] != signature[i]) - matched = false; - if (res.size() != signature.size()) - matched = false; + if (res[i] != signature[i]) matched = false; + if (res.size() != signature.size()) matched = false; if (!matched) { ec = error::signature_verification_error::invalid_signature; return; @@ -728,14 +742,13 @@ namespace jwt { * Returns the algorithm name provided to the constructor * \return algorithm's name */ - std::string name() const { - return alg_name; - } + std::string name() const { return alg_name; } + private: /// HMAC secrect const std::string secret; /// HMAC hash generator - const EVP_MD*(*md)(); + const EVP_MD* (*md)(); /// algorithm's name const std::string alg_name; }; @@ -752,12 +765,12 @@ namespace jwt { * \param md Pointer to hash function * \param name Name of the algorithm */ - rsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, const std::string& private_key_password, const EVP_MD*(*md)(), std::string name) - : md(md), alg_name(std::move(name)) - { + rsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, + const std::string& private_key_password, const EVP_MD* (*md)(), std::string name) + : md(md), alg_name(std::move(name)) { if (!private_key.empty()) { pkey = helper::load_private_key_from_string(private_key, private_key_password); - } else if(!public_key.empty()) { + } else if (!public_key.empty()) { pkey = helper::load_public_key_from_string(public_key, public_key_password); } else throw rsa_exception(error::rsa_error::no_key_provided); @@ -779,7 +792,7 @@ namespace jwt { ec = error::signature_generation_error::create_context_failed; return {}; } - if (!EVP_SignInit(ctx.get(), md())){ + if (!EVP_SignInit(ctx.get(), md())) { ec = error::signature_generation_error::signinit_failed; return {}; } @@ -787,11 +800,11 @@ namespace jwt { std::string res(EVP_PKEY_size(pkey.get()), '\0'); unsigned int len = 0; - if (!EVP_SignUpdate(ctx.get(), data.data(), data.size())){ + if (!EVP_SignUpdate(ctx.get(), data.data(), data.size())) { ec = error::signature_generation_error::signupdate_failed; return {}; } - if (EVP_SignFinal(ctx.get(), (unsigned char*)res.data(), &len, pkey.get()) == 0) { // NOLINT(google-readability-casting) requires `const_cast` + if (EVP_SignFinal(ctx.get(), (unsigned char*)res.data(), &len, pkey.get()) == 0) { ec = error::signature_generation_error::signfinal_failed; return {}; } @@ -824,7 +837,8 @@ namespace jwt { ec = error::signature_verification_error::verifyupdate_failed; return; } - auto res = EVP_VerifyFinal(ctx.get(), reinterpret_cast(signature.data()), static_cast(signature.size()), pkey.get()); + auto res = EVP_VerifyFinal(ctx.get(), reinterpret_cast(signature.data()), + static_cast(signature.size()), pkey.get()); if (res != 1) { ec = error::signature_verification_error::verifyfinal_failed; return; @@ -834,14 +848,13 @@ namespace jwt { * Returns the algorithm name provided to the constructor * \return algorithm's name */ - std::string name() const { - return alg_name; - } + std::string name() const { return alg_name; } + private: /// OpenSSL structure containing converted keys std::shared_ptr pkey; /// Hash generator - const EVP_MD*(*md)(); + const EVP_MD* (*md)(); /// algorithm's name const std::string alg_name; }; @@ -852,57 +865,55 @@ namespace jwt { /** * Construct new ecdsa algorithm * \param public_key ECDSA public key in PEM format - * \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail. - * \param public_key_password Password to decrypt public key pem. - * \param private_key_password Password to decrypt private key pem. - * \param md Pointer to hash function - * \param name Name of the algorithm + * \param private_key ECDSA private key or empty string if not available. If empty, signing will always + * fail. \param public_key_password Password to decrypt public key pem. \param private_key_password Password + * to decrypt private key pem. \param md Pointer to hash function \param name Name of the algorithm */ - ecdsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, const std::string& private_key_password, const EVP_MD*(*md)(), std::string name, size_t siglen) - : md(md), alg_name(std::move(name)), signature_length(siglen) - { + ecdsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, + const std::string& private_key_password, const EVP_MD* (*md)(), std::string name, size_t siglen) + : md(md), alg_name(std::move(name)), signature_length(siglen) { if (!public_key.empty()) { std::unique_ptr pubkey_bio(BIO_new(BIO_s_mem()), BIO_free_all); - if(!pubkey_bio) - throw ecdsa_exception(error::ecdsa_error::create_mem_bio_failed); - if(public_key.substr(0, 27) == "-----BEGIN CERTIFICATE-----") { + if (!pubkey_bio) throw ecdsa_exception(error::ecdsa_error::create_mem_bio_failed); + if (public_key.substr(0, 27) == "-----BEGIN CERTIFICATE-----") { auto epkey = helper::extract_pubkey_from_cert(public_key, public_key_password); const int len = static_cast(epkey.size()); if (BIO_write(pubkey_bio.get(), epkey.data(), len) != len) throw ecdsa_exception(error::ecdsa_error::load_key_bio_write); - } else { + } else { const int len = static_cast(public_key.size()); if (BIO_write(pubkey_bio.get(), public_key.data(), len) != len) throw ecdsa_exception(error::ecdsa_error::load_key_bio_write); } - pkey.reset(PEM_read_bio_EC_PUBKEY(pubkey_bio.get(), nullptr, nullptr, (void*)public_key_password.c_str()), EC_KEY_free); // NOLINT(google-readability-casting) requires `const_cast` - if (!pkey) - throw ecdsa_exception(error::ecdsa_error::load_key_bio_read); + pkey.reset(PEM_read_bio_EC_PUBKEY( + pubkey_bio.get(), nullptr, nullptr, + (void*)public_key_password + .c_str()), // NOLINT(google-readability-casting) requires `const_cast` + EC_KEY_free); + if (!pkey) throw ecdsa_exception(error::ecdsa_error::load_key_bio_read); size_t keysize = EC_GROUP_get_degree(EC_KEY_get0_group(pkey.get())); - if(keysize != signature_length*4 && (signature_length != 132 || keysize != 521)) + if (keysize != signature_length * 4 && (signature_length != 132 || keysize != 521)) throw ecdsa_exception(error::ecdsa_error::invalid_key_size); } if (!private_key.empty()) { std::unique_ptr privkey_bio(BIO_new(BIO_s_mem()), BIO_free_all); - if(!privkey_bio) - throw ecdsa_exception(error::ecdsa_error::create_mem_bio_failed); + if (!privkey_bio) throw ecdsa_exception(error::ecdsa_error::create_mem_bio_failed); const int len = static_cast(private_key.size()); if (BIO_write(privkey_bio.get(), private_key.data(), len) != len) throw ecdsa_exception(error::ecdsa_error::load_key_bio_write); - pkey.reset(PEM_read_bio_ECPrivateKey(privkey_bio.get(), nullptr, nullptr, const_cast(private_key_password.c_str())), EC_KEY_free); - if (!pkey) - throw ecdsa_exception(error::ecdsa_error::load_key_bio_read); + pkey.reset(PEM_read_bio_ECPrivateKey(privkey_bio.get(), nullptr, nullptr, + const_cast(private_key_password.c_str())), + EC_KEY_free); + if (!pkey) throw ecdsa_exception(error::ecdsa_error::load_key_bio_read); size_t keysize = EC_GROUP_get_degree(EC_KEY_get0_group(pkey.get())); - if(keysize != signature_length*4 && (signature_length != 132 || keysize != 521)) + if (keysize != signature_length * 4 && (signature_length != 132 || keysize != 521)) throw ecdsa_exception(error::ecdsa_error::invalid_key_size); } - if(!pkey) - throw ecdsa_exception(error::ecdsa_error::no_key_provided); + if (!pkey) throw ecdsa_exception(error::ecdsa_error::no_key_provided); - if(EC_KEY_check_key(pkey.get()) == 0) - throw ecdsa_exception(error::ecdsa_error::invalid_key); + if (EC_KEY_check_key(pkey.get()) == 0) throw ecdsa_exception(error::ecdsa_error::invalid_key); } /** * Sign jwt data @@ -913,11 +924,13 @@ namespace jwt { std::string sign(const std::string& data, std::error_code& ec) const { ec.clear(); const std::string hash = generate_hash(data, ec); - if(ec) return {}; + if (ec) return {}; - std::unique_ptr - sig(ECDSA_do_sign(reinterpret_cast(hash.data()), static_cast(hash.size()), pkey.get()), ECDSA_SIG_free); - if(!sig) { + std::unique_ptr sig( + ECDSA_do_sign(reinterpret_cast(hash.data()), static_cast(hash.size()), + pkey.get()), + ECDSA_SIG_free); + if (!sig) { ec = error::signature_generation_error::ecdsa_do_sign_failed; return {}; } @@ -926,16 +939,16 @@ namespace jwt { auto rr = helper::bn2raw(sig->r); auto rs = helper::bn2raw(sig->s); #else - const BIGNUM *r; - const BIGNUM *s; + const BIGNUM* r; + const BIGNUM* s; ECDSA_SIG_get0(sig.get(), &r, &s); auto rr = helper::bn2raw(r); auto rs = helper::bn2raw(s); #endif - if(rr.size() > signature_length/2 || rs.size() > signature_length/2) + if (rr.size() > signature_length / 2 || rs.size() > signature_length / 2) throw std::logic_error("bignum size exceeded expected length"); - rr.insert(0, signature_length/2 - rr.size(), '\0'); - rs.insert(0, signature_length/2 - rs.size(), '\0'); + rr.insert(0, signature_length / 2 - rr.size(), '\0'); + rs.insert(0, signature_length / 2 - rs.size(), '\0'); return rr + rs; } @@ -948,7 +961,7 @@ namespace jwt { void verify(const std::string& data, const std::string& signature, std::error_code& ec) const { ec.clear(); const std::string hash = generate_hash(data, ec); - if(ec) return; + if (ec) return; auto r = helper::raw2bn(signature.substr(0, signature.size() / 2)); auto s = helper::raw2bn(signature.substr(signature.size() / 2)); @@ -957,20 +970,22 @@ namespace jwt { sig.r = r.get(); sig.s = s.get(); - if(ECDSA_do_verify((const unsigned char*)hash.data(), static_cast(hash.size()), &sig, pkey.get()) != 1) { + if (ECDSA_do_verify((const unsigned char*)hash.data(), static_cast(hash.size()), &sig, + pkey.get()) != 1) { ec = error::signature_verification_error::invalid_signature; return; } #else std::unique_ptr sig(ECDSA_SIG_new(), ECDSA_SIG_free); - if(!sig) { + if (!sig) { ec = error::signature_verification_error::create_context_failed; return; } ECDSA_SIG_set0(sig.get(), r.release(), s.release()); - if(ECDSA_do_verify(reinterpret_cast(hash.data()), static_cast(hash.size()), sig.get(), pkey.get()) != 1) { + if (ECDSA_do_verify(reinterpret_cast(hash.data()), static_cast(hash.size()), + sig.get(), pkey.get()) != 1) { ec = error::signature_verification_error::invalid_signature; return; } @@ -980,9 +995,8 @@ namespace jwt { * Returns the algorithm name provided to the constructor * \return algorithm's name */ - std::string name() const { - return alg_name; - } + std::string name() const { return alg_name; } + private: /** * Hash the provided data using the hash function specified in constructor @@ -991,25 +1005,29 @@ namespace jwt { */ std::string generate_hash(const std::string& data, std::error_code& ec) const { #ifdef OPENSSL10 - std::unique_ptr ctx(EVP_MD_CTX_create(), &EVP_MD_CTX_destroy); + std::unique_ptr ctx(EVP_MD_CTX_create(), + &EVP_MD_CTX_destroy); #else std::unique_ptr ctx(EVP_MD_CTX_new(), EVP_MD_CTX_free); #endif - if(!ctx) { + if (!ctx) { ec = error::signature_generation_error::create_context_failed; return {}; } - if(EVP_DigestInit(ctx.get(), md()) == 0) { + if (EVP_DigestInit(ctx.get(), md()) == 0) { ec = error::signature_generation_error::digestinit_failed; return {}; } - if(EVP_DigestUpdate(ctx.get(), data.data(), data.size()) == 0) { + if (EVP_DigestUpdate(ctx.get(), data.data(), data.size()) == 0) { ec = error::signature_generation_error::digestupdate_failed; return {}; } unsigned int len = 0; std::string res(EVP_MD_CTX_size(ctx.get()), '\0'); - if(EVP_DigestFinal(ctx.get(), (unsigned char*)res.data(), &len) == 0) { // NOLINT(google-readability-casting) requires `const_cast` + if (EVP_DigestFinal( + ctx.get(), + (unsigned char*)res.data(), // NOLINT(google-readability-casting) requires `const_cast` + &len) == 0) { ec = error::signature_generation_error::digestfinal_failed; return {}; } @@ -1020,7 +1038,7 @@ namespace jwt { /// OpenSSL struct containing keys std::shared_ptr pkey; /// Hash generator function - const EVP_MD*(*md)(); + const EVP_MD* (*md)(); /// algorithm's name const std::string alg_name; /// Length of the resulting signature @@ -1031,29 +1049,30 @@ namespace jwt { /** * \brief Base class for EdDSA family of algorithms * - * The EdDSA algorithms were introduced in [OpenSSL v1.1.1](https://www.openssl.org/news/openssl-1.1.1-notes.html), - * so these algorithms are only available when building against this version or higher. + * The EdDSA algorithms were introduced in [OpenSSL + * v1.1.1](https://www.openssl.org/news/openssl-1.1.1-notes.html), so these algorithms are only available when + * building against this version or higher. */ struct eddsa { /** * Construct new eddsa algorithm * \param public_key EdDSA public key in PEM format - * \param private_key EdDSA private key or empty string if not available. If empty, signing will always fail. + * \param private_key EdDSA private key or empty string if not available. If empty, signing will always + * fail. * \param public_key_password Password to decrypt public key pem. - * \param private_key_password Password to decrypt private key pem. + * \param private_key_password Password + * to decrypt private key pem. * \param md Pointer to hash function * \param name Name of the algorithm */ - eddsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, const std::string& private_key_password, const EVP_MD* (*md)(), std::string name) - : md(md), alg_name(std::move(name)) - { + eddsa(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, + const std::string& private_key_password, const EVP_MD* (*md)(), std::string name) + : md(md), alg_name(std::move(name)) { if (!private_key.empty()) { pkey = helper::load_private_key_from_string(private_key, private_key_password); - } - else if (!public_key.empty()) { + } else if (!public_key.empty()) { pkey = helper::load_public_key_from_string(public_key, public_key_password); - } - else + } else throw ecdsa_exception(error::ecdsa_error::load_key_bio_read); } /** @@ -1077,27 +1096,28 @@ namespace jwt { size_t len = EVP_PKEY_size(pkey.get()); std::string res(len, '\0'); - // LibreSSL is the special kid in the block, as it does not support EVP_DigestSign. - // OpenSSL on the otherhand does not support using EVP_DigestSignUpdate for eddsa, which is why we end up with this mess. - #ifdef LIBRESSL_VERSION_NUMBER +// LibreSSL is the special kid in the block, as it does not support EVP_DigestSign. +// OpenSSL on the otherhand does not support using EVP_DigestSignUpdate for eddsa, which is why we end up with this +// mess. +#ifdef LIBRESSL_VERSION_NUMBER ERR_clear_error(); - if(EVP_DigestSignUpdate(ctx.get(), reinterpret_cast(data.data()), data.size()) != 1) { + if (EVP_DigestSignUpdate(ctx.get(), reinterpret_cast(data.data()), data.size()) != + 1) { std::cout << ERR_error_string(ERR_get_error(), NULL) << std::endl; ec = error::signature_generation_error::signupdate_failed; return {}; } - if(EVP_DigestSignFinal(ctx.get(), reinterpret_cast(&res[0]), &len) != 1) { + if (EVP_DigestSignFinal(ctx.get(), reinterpret_cast(&res[0]), &len) != 1) { ec = error::signature_generation_error::signfinal_failed; return {}; } - #else - if (EVP_DigestSign(ctx.get(), - reinterpret_cast(&res[0]), &len, - reinterpret_cast(data.data()), data.size()) != 1) { +#else + if (EVP_DigestSign(ctx.get(), reinterpret_cast(&res[0]), &len, + reinterpret_cast(data.data()), data.size()) != 1) { ec = error::signature_generation_error::signfinal_failed; return {}; } - #endif +#endif res.resize(len); return res; @@ -1120,34 +1140,36 @@ namespace jwt { ec = error::signature_verification_error::verifyinit_failed; return; } - // LibreSSL is the special kid in the block, as it does not support EVP_DigestVerify. - // OpenSSL on the otherhand does not support using EVP_DigestVerifyUpdate for eddsa, which is why we end up with this mess. - #ifdef LIBRESSL_VERSION_NUMBER - if (EVP_DigestVerifyUpdate(ctx.get(), reinterpret_cast(data.data()), data.size()) != 1) { +// LibreSSL is the special kid in the block, as it does not support EVP_DigestVerify. +// OpenSSL on the otherhand does not support using EVP_DigestVerifyUpdate for eddsa, which is why we end up with this +// mess. +#ifdef LIBRESSL_VERSION_NUMBER + if (EVP_DigestVerifyUpdate(ctx.get(), reinterpret_cast(data.data()), + data.size()) != 1) { ec = error::signature_verification_error::verifyupdate_failed; return; } - if (EVP_DigestVerifyFinal(ctx.get(), reinterpret_cast(signature.data()), signature.size()) != 1) { + if (EVP_DigestVerifyFinal(ctx.get(), reinterpret_cast(signature.data()), + signature.size()) != 1) { ec = error::signature_verification_error::verifyfinal_failed; return; } - #else - auto res = EVP_DigestVerify(ctx.get(), - reinterpret_cast(signature.data()), signature.size(), - reinterpret_cast(data.data()), data.size()); +#else + auto res = EVP_DigestVerify(ctx.get(), reinterpret_cast(signature.data()), + signature.size(), reinterpret_cast(data.data()), + data.size()); if (res != 1) { ec = error::signature_verification_error::verifyfinal_failed; return; } - #endif +#endif } /** * Returns the algorithm name provided to the constructor * \return algorithm's name */ - std::string name() const { - return alg_name; - } + std::string name() const { return alg_name; } + private: /// OpenSSL struct containing keys std::shared_ptr pkey; @@ -1170,12 +1192,12 @@ namespace jwt { * \param md Pointer to hash function * \param name Name of the algorithm */ - pss(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, const std::string& private_key_password, const EVP_MD*(*md)(), std::string name) - : md(md), alg_name(std::move(name)) - { + pss(const std::string& public_key, const std::string& private_key, const std::string& public_key_password, + const std::string& private_key_password, const EVP_MD* (*md)(), std::string name) + : md(md), alg_name(std::move(name)) { if (!private_key.empty()) { pkey = helper::load_private_key_from_string(private_key, private_key_password); - } else if(!public_key.empty()) { + } else if (!public_key.empty()) { pkey = helper::load_public_key_from_string(public_key, public_key_password); } else throw rsa_exception(error::rsa_error::no_key_provided); @@ -1190,23 +1212,27 @@ namespace jwt { std::string sign(const std::string& data, std::error_code& ec) const { ec.clear(); auto hash = this->generate_hash(data, ec); - if(ec) return {}; + if (ec) return {}; std::unique_ptr key(EVP_PKEY_get1_RSA(pkey.get()), RSA_free); - if(!key) { + if (!key) { ec = error::signature_generation_error::get_key_failed; return {}; } const int size = RSA_size(key.get()); std::string padded(size, 0x00); - if (RSA_padding_add_PKCS1_PSS_mgf1(key.get(), (unsigned char*)padded.data(), reinterpret_cast(hash.data()), md(), md(), -1) == 0) { // NOLINT(google-readability-casting) requires `const_cast` + if (RSA_padding_add_PKCS1_PSS_mgf1( + key.get(), (unsigned char*)padded.data(), reinterpret_cast(hash.data()), + md(), md(), -1) == 0) { // NOLINT(google-readability-casting) requires `const_cast` ec = error::signature_generation_error::rsa_padding_failed; return {}; } std::string res(size, 0x00); - if (RSA_private_encrypt(size, reinterpret_cast(padded.data()), (unsigned char*)res.data(), key.get(), RSA_NO_PADDING) < 0) { // NOLINT(google-readability-casting) requires `const_cast` + if (RSA_private_encrypt(size, reinterpret_cast(padded.data()), + (unsigned char*)res.data(), key.get(), RSA_NO_PADDING) < + 0) { // NOLINT(google-readability-casting) requires `const_cast` ec = error::signature_generation_error::rsa_private_encrypt_failed; return {}; } @@ -1222,22 +1248,26 @@ namespace jwt { void verify(const std::string& data, const std::string& signature, std::error_code& ec) const { ec.clear(); auto hash = this->generate_hash(data, ec); - if(ec) return; + if (ec) return; std::unique_ptr key(EVP_PKEY_get1_RSA(pkey.get()), RSA_free); - if(!key) { + if (!key) { ec = error::signature_verification_error::get_key_failed; return; } const int size = RSA_size(key.get()); std::string sig(size, 0x00); - if(RSA_public_decrypt(static_cast(signature.size()), reinterpret_cast(signature.data()), (unsigned char*)sig.data(), key.get(), RSA_NO_PADDING) == 0) {// NOLINT(google-readability-casting) requires `const_cast` + if (RSA_public_decrypt( + static_cast(signature.size()), reinterpret_cast(signature.data()), + (unsigned char*)sig.data(), // NOLINT(google-readability-casting) requires `const_cast` + key.get(), RSA_NO_PADDING) == 0) { ec = error::signature_verification_error::invalid_signature; return; } - if(RSA_verify_PKCS1_PSS_mgf1(key.get(), reinterpret_cast(hash.data()), md(), md(), reinterpret_cast(sig.data()), -1) == 0) { + if (RSA_verify_PKCS1_PSS_mgf1(key.get(), reinterpret_cast(hash.data()), md(), + md(), reinterpret_cast(sig.data()), -1) == 0) { ec = error::signature_verification_error::invalid_signature; return; } @@ -1246,9 +1276,8 @@ namespace jwt { * Returns the algorithm name provided to the constructor * \return algorithm's name */ - std::string name() const { - return alg_name; - } + std::string name() const { return alg_name; } + private: /** * Hash the provided data using the hash function specified in constructor @@ -1257,25 +1286,27 @@ namespace jwt { */ std::string generate_hash(const std::string& data, std::error_code& ec) const { #ifdef OPENSSL10 - std::unique_ptr ctx(EVP_MD_CTX_create(), &EVP_MD_CTX_destroy); + std::unique_ptr ctx(EVP_MD_CTX_create(), + &EVP_MD_CTX_destroy); #else std::unique_ptr ctx(EVP_MD_CTX_new(), EVP_MD_CTX_free); #endif - if(!ctx) { + if (!ctx) { ec = error::signature_generation_error::create_context_failed; return {}; } - if(EVP_DigestInit(ctx.get(), md()) == 0) { + if (EVP_DigestInit(ctx.get(), md()) == 0) { ec = error::signature_generation_error::digestinit_failed; return {}; } - if(EVP_DigestUpdate(ctx.get(), data.data(), data.size()) == 0) { + if (EVP_DigestUpdate(ctx.get(), data.data(), data.size()) == 0) { ec = error::signature_generation_error::digestupdate_failed; return {}; } unsigned int len = 0; std::string res(EVP_MD_CTX_size(ctx.get()), '\0'); - if(EVP_DigestFinal(ctx.get(), (unsigned char*)res.data(), &len) == 0) { // NOLINT(google-readability-casting) requires `const_cast` + if (EVP_DigestFinal(ctx.get(), (unsigned char*)res.data(), &len) == + 0) { // NOLINT(google-readability-casting) requires `const_cast` ec = error::signature_generation_error::digestfinal_failed; return {}; } @@ -1286,7 +1317,7 @@ namespace jwt { /// OpenSSL structure containing keys std::shared_ptr pkey; /// Hash generator function - const EVP_MD*(*md)(); + const EVP_MD* (*md)(); /// algorithm's name const std::string alg_name; }; @@ -1299,9 +1330,7 @@ namespace jwt { * Construct new instance of algorithm * \param key HMAC signing key */ - explicit hs256(std::string key) - : hmacsha(std::move(key), EVP_sha256, "HS256") - {} + explicit hs256(std::string key) : hmacsha(std::move(key), EVP_sha256, "HS256") {} }; /** * HS384 algorithm @@ -1311,9 +1340,7 @@ namespace jwt { * Construct new instance of algorithm * \param key HMAC signing key */ - explicit hs384(std::string key) - : hmacsha(std::move(key), EVP_sha384, "HS384") - {} + explicit hs384(std::string key) : hmacsha(std::move(key), EVP_sha384, "HS384") {} }; /** * HS512 algorithm @@ -1323,9 +1350,7 @@ namespace jwt { * Construct new instance of algorithm * \param key HMAC signing key */ - explicit hs512(std::string key) - : hmacsha(std::move(key), EVP_sha512, "HS512") - {} + explicit hs512(std::string key) : hmacsha(std::move(key), EVP_sha512, "HS512") {} }; /** * RS256 algorithm @@ -1338,9 +1363,9 @@ namespace jwt { * \param public_key_password Password to decrypt public key pem. * \param private_key_password Password to decrypt private key pem. */ - explicit rs256(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") - : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "RS256") - {} + explicit rs256(const std::string& public_key, const std::string& private_key = "", + const std::string& public_key_password = "", const std::string& private_key_password = "") + : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "RS256") {} }; /** * RS384 algorithm @@ -1353,9 +1378,9 @@ namespace jwt { * \param public_key_password Password to decrypt public key pem. * \param private_key_password Password to decrypt private key pem. */ - explicit rs384(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") - : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "RS384") - {} + explicit rs384(const std::string& public_key, const std::string& private_key = "", + const std::string& public_key_password = "", const std::string& private_key_password = "") + : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "RS384") {} }; /** * RS512 algorithm @@ -1368,9 +1393,9 @@ namespace jwt { * \param public_key_password Password to decrypt public key pem. * \param private_key_password Password to decrypt private key pem. */ - explicit rs512(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") - : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "RS512") - {} + explicit rs512(const std::string& public_key, const std::string& private_key = "", + const std::string& public_key_password = "", const std::string& private_key_password = "") + : rsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "RS512") {} }; /** * ES256 algorithm @@ -1379,13 +1404,15 @@ namespace jwt { /** * Construct new instance of algorithm * \param public_key ECDSA public key in PEM format - * \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail. + * \param private_key ECDSA private key or empty string if not available. If empty, signing will always + * fail. * \param public_key_password Password to decrypt public key pem. - * \param private_key_password Password to decrypt private key pem. + * \param private_key_password Password + * to decrypt private key pem. */ - explicit es256(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") - : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "ES256", 64) - {} + explicit es256(const std::string& public_key, const std::string& private_key = "", + const std::string& public_key_password = "", const std::string& private_key_password = "") + : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "ES256", 64) {} }; /** * ES384 algorithm @@ -1394,13 +1421,15 @@ namespace jwt { /** * Construct new instance of algorithm * \param public_key ECDSA public key in PEM format - * \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail. + * \param private_key ECDSA private key or empty string if not available. If empty, signing will always + * fail. * \param public_key_password Password to decrypt public key pem. - * \param private_key_password Password to decrypt private key pem. + * \param private_key_password Password + * to decrypt private key pem. */ - explicit es384(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") - : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "ES384", 96) - {} + explicit es384(const std::string& public_key, const std::string& private_key = "", + const std::string& public_key_password = "", const std::string& private_key_password = "") + : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "ES384", 96) {} }; /** * ES512 algorithm @@ -1409,13 +1438,15 @@ namespace jwt { /** * Construct new instance of algorithm * \param public_key ECDSA public key in PEM format - * \param private_key ECDSA private key or empty string if not available. If empty, signing will always fail. + * \param private_key ECDSA private key or empty string if not available. If empty, signing will always + * fail. * \param public_key_password Password to decrypt public key pem. - * \param private_key_password Password to decrypt private key pem. + * \param private_key_password Password + * to decrypt private key pem. */ - explicit es512(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") - : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "ES512", 132) - {} + explicit es512(const std::string& public_key, const std::string& private_key = "", + const std::string& public_key_password = "", const std::string& private_key_password = "") + : ecdsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "ES512", 132) {} }; #ifndef OPENSSL110 @@ -1428,13 +1459,15 @@ namespace jwt { /** * Construct new instance of algorithm * \param public_key Ed25519 public key in PEM format - * \param private_key Ed25519 private key or empty string if not available. If empty, signing will always fail. + * \param private_key Ed25519 private key or empty string if not available. If empty, signing will always + * fail. * \param public_key_password Password to decrypt public key pem. - * \param private_key_password Password to decrypt private key pem. + * \param private_key_password Password + * to decrypt private key pem. */ - explicit ed25519(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") - : eddsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "EdDSA") - {} + explicit ed25519(const std::string& public_key, const std::string& private_key = "", + const std::string& public_key_password = "", const std::string& private_key_password = "") + : eddsa(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "EdDSA") {} }; /** @@ -1446,13 +1479,15 @@ namespace jwt { /** * Construct new instance of algorithm * \param public_key Ed448 public key in PEM format - * \param private_key Ed448 private key or empty string if not available. If empty, signing will always fail. + * \param private_key Ed448 private key or empty string if not available. If empty, signing will always + * fail. * \param public_key_password Password to decrypt public key pem. - * \param private_key_password Password to decrypt private key pem. + * \param private_key_password Password + * to decrypt private key pem. */ - explicit ed448(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") - : eddsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "EdDSA") - {} + explicit ed448(const std::string& public_key, const std::string& private_key = "", + const std::string& public_key_password = "", const std::string& private_key_password = "") + : eddsa(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "EdDSA") {} }; #endif @@ -1467,9 +1502,9 @@ namespace jwt { * \param public_key_password Password to decrypt public key pem. * \param private_key_password Password to decrypt private key pem. */ - explicit ps256(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") - : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "PS256") - {} + explicit ps256(const std::string& public_key, const std::string& private_key = "", + const std::string& public_key_password = "", const std::string& private_key_password = "") + : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha256, "PS256") {} }; /** * PS384 algorithm @@ -1482,9 +1517,9 @@ namespace jwt { * \param public_key_password Password to decrypt public key pem. * \param private_key_password Password to decrypt private key pem. */ - explicit ps384(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") - : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "PS384") - {} + explicit ps384(const std::string& public_key, const std::string& private_key = "", + const std::string& public_key_password = "", const std::string& private_key_password = "") + : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha384, "PS384") {} }; /** * PS512 algorithm @@ -1497,11 +1532,11 @@ namespace jwt { * \param public_key_password Password to decrypt public key pem. * \param private_key_password Password to decrypt private key pem. */ - explicit ps512(const std::string& public_key, const std::string& private_key = "", const std::string& public_key_password = "", const std::string& private_key_password = "") - : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "PS512") - {} + explicit ps512(const std::string& public_key, const std::string& private_key = "", + const std::string& public_key_password = "", const std::string& private_key_password = "") + : pss(public_key, private_key, public_key_password, private_key_password, EVP_sha512, "PS512") {} }; - } // namespace algorithm + } // namespace algorithm /** * \brief JSON Abstractions for working with any library @@ -1512,29 +1547,21 @@ namespace jwt { * * This enum is to abstract the third party underlying types */ - enum class type { - boolean, - integer, - number, - string, - array, - object - }; - } // namespace json + enum class type { boolean, integer, number, string, array, object }; + } // namespace json namespace details { #ifdef __cpp_lib_void_t - template + template using void_t = std::void_t; #else // https://en.cppreference.com/w/cpp/types/void_t - template - struct make_void - { + template + struct make_void { using type = void; }; - template + template using void_t = typename make_void::type; #endif @@ -1545,8 +1572,7 @@ namespace jwt { template class _Op, typename... _Args> using is_detected_t = std::experimental::detected_t<_Op, _Args...>; #else - struct nonesuch - { + struct nonesuch { nonesuch() = delete; ~nonesuch() = delete; nonesuch(nonesuch const&) = delete; @@ -1556,145 +1582,152 @@ namespace jwt { }; // https://en.cppreference.com/w/cpp/experimental/is_detected - template class Op, class... Args> - struct detector - { + template class Op, class... Args> + struct detector { using value = std::false_type; using type = Default; }; - template class Op, class... Args> - struct detector>, Op, Args...> - { + template class Op, class... Args> + struct detector>, Op, Args...> { using value = std::true_type; using type = Op; }; - template