userver: userver/crypto/jwt.hpp Source File
Loading...
Searching...
No Matches
jwt.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/crypto/jwt.hpp
4/// @brief Creation, parsing and verification of signed JSON Web Tokens
5/// @ingroup userver_universal
6/// @see @ref scripts/docs/en/userver/jwt.md
7
8#include <chrono>
9#include <optional>
10#include <string>
11#include <string_view>
12#include <unordered_map>
13#include <unordered_set>
14
15#include <userver/crypto/exception.hpp>
16#include <userver/formats/json/value.hpp>
17#include <userver/formats/parse/to.hpp>
18#include <userver/formats/serialize/to.hpp>
19
20USERVER_NAMESPACE_BEGIN
21
22namespace crypto {
23
24class Signer;
25class Verifier;
26
27} // namespace crypto
28
29/// @brief Signed JWTs in the three-part JWS compact serialization.
30namespace crypto::jwt {
31
32/// @brief JOSE header parameters for a compact signed JWT.
33struct JoseHeader {
34 std::string algorithm; ///< Signing algorithm (`alg`).
35 std::optional<std::string> type{}; ///< Token media type (`typ`).
36 std::optional<std::string> content_type{}; ///< Payload media type (`cty`).
37 std::optional<std::string> key_id{}; ///< Key identifier (`kid`).
38 /// Additional noncritical parameters with their original JSON values.
39 std::unordered_map<std::string, formats::json::Value> extensions{};
40};
41
42/// Parses the JOSE header from a JSON object.
43JoseHeader Parse(const formats::json::Value& value, formats::parse::To<JoseHeader>);
44
45/// Serializes a JOSE header to a JSON object, omitting absent parameters.
46formats::json::Value Serialize(const JoseHeader& header, formats::serialize::To<formats::json::Value>);
47
48/// @brief Header and claims returned by @ref crypto::jwt::Verify.
49struct Token {
50 JoseHeader header;
51 formats::json::Value payload;
52};
53
54/// Whether verification requires an expiration claim.
55enum class ExpirationPolicy {
56 kRequired, ///< Reject tokens without an `exp` claim.
57 kOptional, ///< Allow missing `exp`, but validate it whenever present.
58};
59
60/// @brief Claim checks performed by @ref crypto::jwt::Verify after signature verification.
62 /// Expected `iss`. When set, the claim must be present and match exactly.
63 std::optional<std::string> issuer{};
64 /// Accepted audiences. A present `aud` must match at least one entry.
65 /// An empty set accepts only tokens without `aud`; a nonempty set requires `aud`.
66 std::unordered_set<std::string> audiences{};
67 /// Expected `sub`. When set, the claim must be present and match exactly.
68 std::optional<std::string> subject{};
69 /// Expected token media type (`typ`). Compares the name case-insensitively and ignores parameters.
70 std::optional<std::string> type{};
71 /// Nonnegative clock skew allowance for `exp`, `nbf`, and `iat`.
72 std::chrono::seconds leeway{0};
73 /// Expiration is required by default for authorization tokens.
75};
76
77/// @brief Signs the supplied claims with `typ: JWT` and the signer's algorithm.
78/// Checks registered claim types before signing.
79/// @pre A custom HMAC signer produces the full MAC for its declared algorithm.
80/// @pre The caller supplies an HMAC key of at least 32 bytes for HS256, 48 for HS384, or 64 for HS512.
81/// @pre Every JSON object in @a payload has unique member names, including nested objects.
82/// @throws crypto::SignError for an unsupported algorithm, invalid claims, or a signing failure.
83std::string MakeToken(const formats::json::Value& payload, const crypto::Signer& signer);
84
85/// @brief Creates a compact token from the exact bytes of a serialized JSON payload.
86/// The header contains `typ: JWT` followed by the signer's `alg`.
87/// Any @ref crypto::Signer is accepted, including @ref crypto::SignerNone for unsigned tokens.
88/// The caller is responsible for validating registered claims.
89/// @pre @a json_payload contains valid JSON with unique object member names.
90std::string MakeToken(std::string_view json_payload, const crypto::Signer& signer);
91
92/// @overload
93/// Appends `kid` to the header, including when @a key_id is empty.
94std::string MakeToken(std::string_view json_payload, const crypto::Signer& signer, std::string_view key_id);
95
96/// @brief Reads the unverified JOSE header from a compact JWT for key selection.
97/// Checks the three-part structure and decodes only the header. The returned algorithm may be unknown.
98/// Pass the original token to @ref crypto::jwt::Verify to check the algorithm, signature, and claims.
99/// @throws crypto::VerificationError for malformed compact structure, invalid header parameters,
100/// unsupported critical or unencoded-payload extensions, or a nested JWT content type.
101JoseHeader UnverifiedParseJoseHeader(std::string_view token);
102
103/// @brief Verifies a JWT with the application's trusted key and algorithm, then validates its registered claims.
104/// @pre A custom HMAC verifier checks the full MAC, including its length.
105/// @pre The caller supplies an HMAC key meeting the minimum length documented in @ref crypto::jwt::MakeToken.
106/// @throws crypto::VerificationError if parsing, signature verification, or claim checks fail.
107/// @throws std::invalid_argument if @a options contains a negative leeway.
108Token Verify(std::string_view token, const crypto::Verifier& verifier, const VerificationOptions& options = {});
109
110} // namespace crypto::jwt
111
112USERVER_NAMESPACE_END