cxxmcp 1.1.6
C++ MCP SDK
Loading...
Searching...
No Matches
pkce.hpp
Go to the documentation of this file.
1// Copyright (c) 2025 [caomengxuan666]
2
3#pragma once
4
5#include <openssl/rand.h>
6
7#include <array>
8#include <cstddef>
9#include <string>
10
13#include "cxxmcp/auth/pkce.hpp"
14#include "cxxmcp/auth/types.hpp"
16
19
20namespace mcp::auth::openssl {
21
24inline constexpr std::size_t kPkceVerifierBytes = 32;
25
30class OpenSslPkceGenerator final : public PkceGenerator {
31 public:
32 core::Result<PkceChallenge> create_s256() override {
33 std::array<unsigned char, kPkceVerifierBytes> random_bytes{};
34 if (RAND_bytes(random_bytes.data(),
35 static_cast<int>(random_bytes.size())) != 1) {
36 return core::unexpected(
38 "failed to generate PKCE code_verifier random bytes",
39 {},
40 std::string(AuthErrorCategory)});
41 }
42
43 PkceChallenge challenge;
44 challenge.code_verifier =
45 base64url_encode_bytes(random_bytes.data(), random_bytes.size());
46 challenge.method = PkceCodeChallengeMethod::kS256;
47
48 auto hashed = sha256_base64url(challenge.code_verifier);
49 if (!hashed.has_value()) {
50 return core::unexpected(hashed.error());
51 }
52 challenge.code_challenge = std::move(*hashed);
53
54 return challenge;
55 }
56
57 core::Result<bool> verify(const PkceChallenge& challenge) override {
58 if (challenge.method != PkceCodeChallengeMethod::kS256) {
59 return core::unexpected(core::Error{
60 0,
61 "unsupported PKCE code_challenge_method; only S256 is supported",
62 {},
63 std::string(AuthErrorCategory)});
64 }
65
66 auto expected = sha256_base64url(challenge.code_verifier);
67 if (!expected.has_value()) {
68 return core::unexpected(expected.error());
69 }
70
71 return *expected == challenge.code_challenge;
72 }
73};
74
75} // namespace mcp::auth::openssl
Shared lightweight value types for cxxmcp auth contracts.
JOSE base64url helpers shared by optional OpenSSL auth code.
Public wrapper around the SDK's private PKCE implementation.
Definition pkce.hpp:30
OpenSSL-backed implementation of the PkceGenerator contract.
Definition pkce.hpp:30
constexpr std::size_t kPkceVerifierBytes
PKCE code_verifier length in bytes (43 characters when base64url encoded, satisfying RFC 7636 ยง4....
Definition pkce.hpp:24
PKCE contracts for OAuth authorization-code flows.
Shared result and error primitives used by the public cxxmcp SDK.
tl::expected< T, Error > Result
Alias for the SDK result type.
Definition result.hpp:64
OpenSSL-backed SHA-256 helpers for optional auth crypto.
core::Result< std::string > sha256_base64url(std::string_view data)
Compute base64url(SHA-256(data)).
Definition sha256.hpp:21
PKCE verifier/challenge pair used by OAuth 2.1 authorization flows.
Definition pkce.hpp:19
Structured error returned by fallible SDK operations.
Definition result.hpp:35