jwt_auth.h 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. #ifndef JWT_AUTH_H
  2. #define JWT_AUTH_H
  3. #include <string>
  4. #include <vector>
  5. #include <map>
  6. #include <chrono>
  7. #include <memory>
  8. /**
  9. * @brief JWT (JSON Web Token) authentication implementation
  10. *
  11. * This class provides JWT token generation and validation functionality
  12. * for the stable-diffusion.cpp-rest server. It supports HS256 algorithm
  13. * and includes claims for user identification, expiration, and roles.
  14. */
  15. class JWTAuth {
  16. public:
  17. /**
  18. * @brief JWT token claims structure
  19. */
  20. struct Claims {
  21. std::string userId; ///< User identifier
  22. std::string username; ///< Username
  23. std::string role; ///< User role (admin, user, etc.)
  24. std::vector<std::string> permissions; ///< User permissions
  25. int64_t issuedAt; ///< Issued at timestamp
  26. int64_t expiresAt; ///< Expiration timestamp
  27. std::string issuer; ///< Token issuer
  28. std::string audience; ///< Token audience
  29. };
  30. /**
  31. * @brief Authentication result structure
  32. */
  33. struct AuthResult {
  34. bool success; ///< Authentication success status
  35. std::string userId; ///< User ID if successful
  36. std::string username; ///< Username if successful
  37. std::string role; ///< User role if successful
  38. std::vector<std::string> permissions; ///< Permissions if successful
  39. std::string errorMessage; ///< Error message if failed
  40. std::string errorCode; ///< Error code for API responses
  41. };
  42. /**
  43. * @brief Construct a new JWT Auth object
  44. *
  45. * @param secret Secret key for signing tokens
  46. * @param tokenExpirationMinutes Token expiration time in minutes (default: 60)
  47. * @param issuer Token issuer (default: "stable-diffusion-rest")
  48. */
  49. explicit JWTAuth(const std::string& secret,
  50. int tokenExpirationMinutes = 60,
  51. const std::string& issuer = "stable-diffusion-rest");
  52. /**
  53. * @brief Destroy the JWT Auth object
  54. */
  55. ~JWTAuth();
  56. /**
  57. * @brief Generate a JWT token for the given user
  58. *
  59. * @param userId User identifier
  60. * @param username Username
  61. * @param role User role
  62. * @param permissions User permissions list
  63. * @return std::string JWT token string, empty on failure
  64. */
  65. std::string generateToken(const std::string& userId,
  66. const std::string& username,
  67. const std::string& role,
  68. const std::vector<std::string>& permissions = {});
  69. /**
  70. * @brief Validate a JWT token and extract claims
  71. *
  72. * @param token JWT token string
  73. * @return AuthResult Authentication result with user information
  74. */
  75. AuthResult validateToken(const std::string& token);
  76. /**
  77. * @brief Refresh an existing token (extend expiration)
  78. *
  79. * @param token Existing JWT token
  80. * @return std::string New JWT token, empty on failure
  81. */
  82. std::string refreshToken(const std::string& token);
  83. /**
  84. * @brief Extract token from Authorization header
  85. *
  86. * @param authHeader Authorization header value
  87. * @return std::string Token string, empty if not found or invalid format
  88. */
  89. static std::string extractTokenFromHeader(const std::string& authHeader);
  90. /**
  91. * @brief Check if user has required permission
  92. *
  93. * @param permissions User permissions list
  94. * @param requiredPermission Required permission to check
  95. * @return true if user has permission, false otherwise
  96. */
  97. static bool hasPermission(const std::vector<std::string>& permissions,
  98. const std::string& requiredPermission);
  99. /**
  100. * @brief Check if user has any of the required permissions
  101. *
  102. * @param permissions User permissions list
  103. * @param requiredPermissions List of permissions to check (any one is sufficient)
  104. * @return true if user has any of the permissions, false otherwise
  105. */
  106. static bool hasAnyPermission(const std::vector<std::string>& permissions,
  107. const std::vector<std::string>& requiredPermissions);
  108. /**
  109. * @brief Get token expiration time
  110. *
  111. * @param token JWT token string
  112. * @return int64_t Expiration timestamp, 0 on failure
  113. */
  114. int64_t getTokenExpiration(const std::string& token);
  115. /**
  116. * @brief Check if token is expired
  117. *
  118. * @param token JWT token string
  119. * @return true if token is expired, false otherwise
  120. */
  121. bool isTokenExpired(const std::string& token);
  122. /**
  123. * @brief Set token expiration time
  124. *
  125. * @param minutes Expiration time in minutes
  126. */
  127. void setTokenExpiration(int minutes);
  128. /**
  129. * @brief Get token expiration time in minutes
  130. *
  131. * @return int Token expiration time in minutes
  132. */
  133. int getTokenExpiration() const;
  134. /**
  135. * @brief Set issuer for tokens
  136. *
  137. * @param issuer Issuer string
  138. */
  139. void setIssuer(const std::string& issuer);
  140. /**
  141. * @brief Get issuer string
  142. *
  143. * @return std::string Issuer string
  144. */
  145. std::string getIssuer() const;
  146. /**
  147. * @brief Generate a random API key
  148. *
  149. * @param length Length of the API key (default: 32)
  150. * @return std::string Random API key
  151. */
  152. static std::string generateApiKey(int length = 32);
  153. /**
  154. * @brief Validate API key format
  155. *
  156. * @param apiKey API key string
  157. * @return true if format is valid, false otherwise
  158. */
  159. static bool validateApiKeyFormat(const std::string& apiKey);
  160. private:
  161. std::string m_secret; ///< Secret key for signing
  162. int m_tokenExpirationMinutes; ///< Token expiration in minutes
  163. std::string m_issuer; ///< Token issuer
  164. /**
  165. * @brief Base64 URL encode a string
  166. *
  167. * @param input Input string
  168. * @return std::string Base64 URL encoded string
  169. */
  170. static std::string base64UrlEncode(const std::string& input);
  171. /**
  172. * @brief Base64 URL decode a string
  173. *
  174. * @param input Base64 URL encoded string
  175. * @return std::string Decoded string
  176. */
  177. static std::string base64UrlDecode(const std::string& input);
  178. /**
  179. * @brief Create JWT header
  180. *
  181. * @return std::string JWT header JSON string
  182. */
  183. std::string createHeader() const;
  184. /**
  185. * @brief Create JWT payload from claims
  186. *
  187. * @param claims Token claims
  188. * @return std::string JWT payload JSON string
  189. */
  190. std::string createPayload(const Claims& claims) const;
  191. /**
  192. * @brief Parse JWT payload from token
  193. *
  194. * @param token JWT token
  195. * @return Claims Parsed claims, empty on failure
  196. */
  197. Claims parsePayload(const std::string& token) const;
  198. /**
  199. * @brief Create HMAC-SHA256 signature
  200. *
  201. * @param header Payload header
  202. * @param payload Payload data
  203. * @return std::string Signature string
  204. */
  205. std::string createSignature(const std::string& header, const std::string& payload) const;
  206. /**
  207. * @brief Verify HMAC-SHA256 signature
  208. *
  209. * @param header Payload header
  210. * @param payload Payload data
  211. * @param signature Signature to verify
  212. * @return true if signature is valid, false otherwise
  213. */
  214. bool verifySignature(const std::string& header, const std::string& payload, const std::string& signature) const;
  215. /**
  216. * @brief Split JWT token into parts
  217. *
  218. * @param token JWT token
  219. * @return std::vector<std::string> Token parts (header, payload, signature)
  220. */
  221. static std::vector<std::string> splitToken(const std::string& token);
  222. /**
  223. * @brief Get current timestamp in seconds
  224. *
  225. * @return int64_t Current timestamp
  226. */
  227. static int64_t getCurrentTimestamp();
  228. /**
  229. * @brief Generate random string
  230. *
  231. * @param length Length of the string
  232. * @return std::string Random string
  233. */
  234. static std::string generateRandomString(int length);
  235. };
  236. #endif // JWT_AUTH_H