jwt_auth.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. #include "jwt_auth.h"
  2. #include <openssl/hmac.h>
  3. #include <openssl/sha.h>
  4. #include <openssl/rand.h>
  5. #include <nlohmann/json.hpp>
  6. #include <sstream>
  7. #include <iomanip>
  8. #include <algorithm>
  9. #include <cctype>
  10. JWTAuth::JWTAuth(const std::string& secret,
  11. int tokenExpirationMinutes,
  12. const std::string& issuer,
  13. const std::string& audience)
  14. : m_secret(secret)
  15. , m_tokenExpirationMinutes(tokenExpirationMinutes)
  16. , m_issuer(issuer)
  17. , m_audience(audience)
  18. {
  19. // Generate random secret if not provided
  20. if (m_secret.empty()) {
  21. m_secret = generateRandomString(64);
  22. }
  23. }
  24. JWTAuth::~JWTAuth() = default;
  25. std::string JWTAuth::generateToken(const std::string& userId,
  26. const std::string& username,
  27. const std::string& role,
  28. const std::vector<std::string>& permissions) {
  29. try {
  30. // Create claims
  31. Claims claims;
  32. claims.userId = userId;
  33. claims.username = username;
  34. claims.role = role;
  35. claims.permissions = permissions;
  36. claims.issuedAt = getCurrentTimestamp();
  37. claims.expiresAt = claims.issuedAt + (m_tokenExpirationMinutes * 60);
  38. claims.issuer = m_issuer;
  39. claims.audience = m_audience;
  40. // Create header and payload
  41. std::string header = createHeader();
  42. std::string payload = createPayload(claims);
  43. // Create signature
  44. std::string signature = createSignature(header, payload);
  45. // Combine parts
  46. return header + "." + payload + "." + signature;
  47. } catch (const std::exception& e) {
  48. return "";
  49. }
  50. }
  51. JWTAuth::AuthResult JWTAuth::validateToken(const std::string& token) {
  52. AuthResult result;
  53. result.success = false;
  54. try {
  55. // Split token
  56. auto parts = splitToken(token);
  57. if (parts.size() != 3) {
  58. result.errorMessage = "Invalid token format";
  59. result.errorCode = "INVALID_TOKEN_FORMAT";
  60. return result;
  61. }
  62. const std::string& header = parts[0];
  63. const std::string& payload = parts[1];
  64. const std::string& signature = parts[2];
  65. // Verify signature
  66. if (!verifySignature(header, payload, signature)) {
  67. result.errorMessage = "Invalid token signature";
  68. result.errorCode = "INVALID_SIGNATURE";
  69. return result;
  70. }
  71. // Parse payload
  72. Claims claims = parsePayload(token);
  73. if (claims.userId.empty()) {
  74. result.errorMessage = "Invalid token payload";
  75. result.errorCode = "INVALID_PAYLOAD";
  76. return result;
  77. }
  78. // Check expiration
  79. if (getCurrentTimestamp() >= claims.expiresAt) {
  80. result.errorMessage = "Token has expired";
  81. result.errorCode = "TOKEN_EXPIRED";
  82. return result;
  83. }
  84. // Check issuer
  85. if (!claims.issuer.empty() && claims.issuer != m_issuer) {
  86. result.errorMessage = "Invalid token issuer";
  87. result.errorCode = "INVALID_ISSUER";
  88. return result;
  89. }
  90. // Token is valid
  91. result.success = true;
  92. result.userId = claims.userId;
  93. result.username = claims.username;
  94. result.role = claims.role;
  95. result.permissions = claims.permissions;
  96. } catch (const std::exception& e) {
  97. result.errorMessage = "Token validation failed: " + std::string(e.what());
  98. result.errorCode = "VALIDATION_ERROR";
  99. }
  100. return result;
  101. }
  102. std::string JWTAuth::refreshToken(const std::string& token) {
  103. try {
  104. // Validate current token
  105. AuthResult result = validateToken(token);
  106. if (!result.success) {
  107. return "";
  108. }
  109. // Generate new token with same claims
  110. return generateToken(result.userId, result.username, result.role, result.permissions);
  111. } catch (const std::exception& e) {
  112. return "";
  113. }
  114. }
  115. std::string JWTAuth::extractTokenFromHeader(const std::string& authHeader) {
  116. if (authHeader.empty()) {
  117. return "";
  118. }
  119. // Check for "Bearer " prefix
  120. const std::string bearerPrefix = "Bearer ";
  121. if (authHeader.length() > bearerPrefix.length() &&
  122. authHeader.substr(0, bearerPrefix.length()) == bearerPrefix) {
  123. return authHeader.substr(bearerPrefix.length());
  124. }
  125. return "";
  126. }
  127. bool JWTAuth::hasPermission(const std::vector<std::string>& permissions,
  128. const std::string& requiredPermission) {
  129. return std::find(permissions.begin(), permissions.end(), requiredPermission) != permissions.end();
  130. }
  131. bool JWTAuth::hasAnyPermission(const std::vector<std::string>& permissions,
  132. const std::vector<std::string>& requiredPermissions) {
  133. for (const auto& permission : requiredPermissions) {
  134. if (hasPermission(permissions, permission)) {
  135. return true;
  136. }
  137. }
  138. return false;
  139. }
  140. int64_t JWTAuth::getTokenExpiration(const std::string& token) {
  141. try {
  142. Claims claims = parsePayload(token);
  143. return claims.expiresAt;
  144. } catch (const std::exception& e) {
  145. return 0;
  146. }
  147. }
  148. bool JWTAuth::isTokenExpired(const std::string& token) {
  149. int64_t expiration = getTokenExpiration(token);
  150. return expiration > 0 && getCurrentTimestamp() >= expiration;
  151. }
  152. void JWTAuth::setTokenExpiration(int minutes) {
  153. m_tokenExpirationMinutes = minutes;
  154. }
  155. int JWTAuth::getTokenExpiration() const {
  156. return m_tokenExpirationMinutes;
  157. }
  158. void JWTAuth::setIssuer(const std::string& issuer) {
  159. m_issuer = issuer;
  160. }
  161. std::string JWTAuth::getIssuer() const {
  162. return m_issuer;
  163. }
  164. std::string JWTAuth::generateApiKey(int length) {
  165. return generateRandomString(length);
  166. }
  167. bool JWTAuth::validateApiKeyFormat(const std::string& apiKey) {
  168. if (apiKey.length() < 16 || apiKey.length() > 128) {
  169. return false;
  170. }
  171. // Check for alphanumeric characters only
  172. for (char c : apiKey) {
  173. if (!std::isalnum(c)) {
  174. return false;
  175. }
  176. }
  177. return true;
  178. }
  179. std::string JWTAuth::base64UrlEncode(const std::string& input) {
  180. const std::string base64Chars =
  181. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
  182. std::string result;
  183. int val = 0, valb = -6;
  184. for (unsigned char c : input) {
  185. val = (val << 8) + c;
  186. valb += 8;
  187. while (valb >= 0) {
  188. result.push_back(base64Chars[(val >> valb) & 0x3F]);
  189. valb -= 6;
  190. }
  191. }
  192. if (valb > -6) {
  193. result.push_back(base64Chars[((val << 8) >> (valb + 8)) & 0x3F]);
  194. }
  195. return result;
  196. }
  197. std::string JWTAuth::base64UrlDecode(const std::string& input) {
  198. const std::string base64Chars =
  199. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
  200. std::string result;
  201. int val = 0, valb = -8;
  202. for (char c : input) {
  203. if (c == '=') continue;
  204. size_t pos = base64Chars.find(c);
  205. if (pos == std::string::npos) return "";
  206. val = (val << 6) + pos;
  207. valb += 6;
  208. if (valb >= 0) {
  209. result.push_back(char((val >> valb) & 0xFF));
  210. valb -= 8;
  211. }
  212. }
  213. return result;
  214. }
  215. std::string JWTAuth::createHeader() const {
  216. nlohmann::json header = {
  217. {"alg", "HS256"},
  218. {"typ", "JWT"}
  219. };
  220. return base64UrlEncode(header.dump());
  221. }
  222. std::string JWTAuth::createPayload(const Claims& claims) const {
  223. nlohmann::json payload = {
  224. {"sub", claims.userId},
  225. {"username", claims.username},
  226. {"role", claims.role},
  227. {"iat", claims.issuedAt},
  228. {"exp", claims.expiresAt},
  229. {"iss", claims.issuer},
  230. {"aud", claims.audience}
  231. };
  232. // Add permissions if not empty
  233. if (!claims.permissions.empty()) {
  234. payload["permissions"] = claims.permissions;
  235. }
  236. return base64UrlEncode(payload.dump());
  237. }
  238. JWTAuth::Claims JWTAuth::parsePayload(const std::string& token) const {
  239. Claims claims;
  240. try {
  241. auto parts = splitToken(token);
  242. if (parts.size() != 3) {
  243. return claims;
  244. }
  245. std::string payloadStr = base64UrlDecode(parts[1]);
  246. nlohmann::json payload = nlohmann::json::parse(payloadStr);
  247. claims.userId = payload.value("sub", "");
  248. claims.username = payload.value("username", "");
  249. claims.role = payload.value("role", "");
  250. claims.issuedAt = payload.value("iat", 0);
  251. claims.expiresAt = payload.value("exp", 0);
  252. claims.issuer = payload.value("iss", "");
  253. claims.audience = payload.value("aud", "");
  254. if (payload.contains("permissions") && payload["permissions"].is_array()) {
  255. for (const auto& perm : payload["permissions"]) {
  256. claims.permissions.push_back(perm.get<std::string>());
  257. }
  258. }
  259. } catch (const std::exception& e) {
  260. // Return empty claims on error
  261. }
  262. return claims;
  263. }
  264. std::string JWTAuth::createSignature(const std::string& header, const std::string& payload) const {
  265. std::string data = header + "." + payload;
  266. unsigned char* digest = HMAC(EVP_sha256(),
  267. m_secret.c_str(), m_secret.length(),
  268. (unsigned char*)data.c_str(), data.length(),
  269. nullptr, nullptr);
  270. return base64UrlEncode(std::string((char*)digest, SHA256_DIGEST_LENGTH));
  271. }
  272. bool JWTAuth::verifySignature(const std::string& header, const std::string& payload, const std::string& signature) const {
  273. std::string expectedSignature = createSignature(header, payload);
  274. return expectedSignature == signature;
  275. }
  276. std::vector<std::string> JWTAuth::splitToken(const std::string& token) {
  277. std::vector<std::string> parts;
  278. std::stringstream ss(token);
  279. std::string part;
  280. while (std::getline(ss, part, '.')) {
  281. parts.push_back(part);
  282. }
  283. return parts;
  284. }
  285. int64_t JWTAuth::getCurrentTimestamp() {
  286. return std::chrono::duration_cast<std::chrono::seconds>(
  287. std::chrono::system_clock::now().time_since_epoch()).count();
  288. }
  289. std::string JWTAuth::generateRandomString(int length) {
  290. const std::string chars =
  291. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  292. std::string result;
  293. result.reserve(length);
  294. for (int i = 0; i < length; ++i) {
  295. unsigned char randomByte;
  296. if (RAND_bytes(&randomByte, 1) != 1) {
  297. return "";
  298. }
  299. result += chars[randomByte % chars.length()];
  300. }
  301. return result;
  302. }