jwt_auth.h 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. * @param audience Token audience (default: "stable-diffusion-rest")
  49. */
  50. explicit JWTAuth(const std::string& secret,
  51. int tokenExpirationMinutes = 60,
  52. const std::string& issuer = "stable-diffusion-rest",
  53. const std::string& audience = "stable-diffusion-rest");
  54. /**
  55. * @brief Destroy the JWT Auth object
  56. */
  57. ~JWTAuth();
  58. /**
  59. * @brief Generate a JWT token for the given user
  60. *
  61. * @param userId User identifier
  62. * @param username Username
  63. * @param role User role
  64. * @param permissions User permissions list
  65. * @return std::string JWT token string, empty on failure
  66. */
  67. std::string generateToken(const std::string& userId,
  68. const std::string& username,
  69. const std::string& role,
  70. const std::vector<std::string>& permissions = {});
  71. /**
  72. * @brief Validate a JWT token and extract claims
  73. *
  74. * @param token JWT token string
  75. * @return AuthResult Authentication result with user information
  76. */
  77. AuthResult validateToken(const std::string& token);
  78. /**
  79. * @brief Refresh an existing token (extend expiration)
  80. *
  81. * @param token Existing JWT token
  82. * @return std::string New JWT token, empty on failure
  83. */
  84. std::string refreshToken(const std::string& token);
  85. /**
  86. * @brief Extract token from Authorization header
  87. *
  88. * @param authHeader Authorization header value
  89. * @return std::string Token string, empty if not found or invalid format
  90. */
  91. static std::string extractTokenFromHeader(const std::string& authHeader);
  92. /**
  93. * @brief Check if user has required permission
  94. *
  95. * @param permissions User permissions list
  96. * @param requiredPermission Required permission to check
  97. * @return true if user has permission, false otherwise
  98. */
  99. static bool hasPermission(const std::vector<std::string>& permissions,
  100. const std::string& requiredPermission);
  101. /**
  102. * @brief Check if user has any of the required permissions
  103. *
  104. * @param permissions User permissions list
  105. * @param requiredPermissions List of permissions to check (any one is sufficient)
  106. * @return true if user has any of the permissions, false otherwise
  107. */
  108. static bool hasAnyPermission(const std::vector<std::string>& permissions,
  109. const std::vector<std::string>& requiredPermissions);
  110. /**
  111. * @brief Get token expiration time
  112. *
  113. * @param token JWT token string
  114. * @return int64_t Expiration timestamp, 0 on failure
  115. */
  116. int64_t getTokenExpiration(const std::string& token);
  117. /**
  118. * @brief Check if token is expired
  119. *
  120. * @param token JWT token string
  121. * @return true if token is expired, false otherwise
  122. */
  123. bool isTokenExpired(const std::string& token);
  124. /**
  125. * @brief Set token expiration time
  126. *
  127. * @param minutes Expiration time in minutes
  128. */
  129. void setTokenExpiration(int minutes);
  130. /**
  131. * @brief Get token expiration time in minutes
  132. *
  133. * @return int Token expiration time in minutes
  134. */
  135. int getTokenExpiration() const;
  136. /**
  137. * @brief Set issuer for tokens
  138. *
  139. * @param issuer Issuer string
  140. */
  141. void setIssuer(const std::string& issuer);
  142. /**
  143. * @brief Get issuer string
  144. *
  145. * @return std::string Issuer string
  146. */
  147. std::string getIssuer() const;
  148. /**
  149. * @brief Generate a random API key
  150. *
  151. * @param length Length of the API key (default: 32)
  152. * @return std::string Random API key
  153. */
  154. static std::string generateApiKey(int length = 32);
  155. /**
  156. * @brief Validate API key format
  157. *
  158. * @param apiKey API key string
  159. * @return true if format is valid, false otherwise
  160. */
  161. static bool validateApiKeyFormat(const std::string& apiKey);
  162. private:
  163. std::string m_secret; ///< Secret key for signing
  164. int m_tokenExpirationMinutes; ///< Token expiration in minutes
  165. std::string m_issuer; ///< Token issuer
  166. std::string m_audience; ///< Token audience
  167. /**
  168. * @brief Base64 URL encode a string
  169. *
  170. * @param input Input string
  171. * @return std::string Base64 URL encoded string
  172. */
  173. static std::string base64UrlEncode(const std::string& input);
  174. /**
  175. * @brief Base64 URL decode a string
  176. *
  177. * @param input Base64 URL encoded string
  178. * @return std::string Decoded string
  179. */
  180. static std::string base64UrlDecode(const std::string& input);
  181. /**
  182. * @brief Create JWT header
  183. *
  184. * @return std::string JWT header JSON string
  185. */
  186. std::string createHeader() const;
  187. /**
  188. * @brief Create JWT payload from claims
  189. *
  190. * @param claims Token claims
  191. * @return std::string JWT payload JSON string
  192. */
  193. std::string createPayload(const Claims& claims) const;
  194. /**
  195. * @brief Parse JWT payload from token
  196. *
  197. * @param token JWT token
  198. * @return Claims Parsed claims, empty on failure
  199. */
  200. Claims parsePayload(const std::string& token) const;
  201. /**
  202. * @brief Create HMAC-SHA256 signature
  203. *
  204. * @param header Payload header
  205. * @param payload Payload data
  206. * @return std::string Signature string
  207. */
  208. std::string createSignature(const std::string& header, const std::string& payload) const;
  209. /**
  210. * @brief Verify HMAC-SHA256 signature
  211. *
  212. * @param header Payload header
  213. * @param payload Payload data
  214. * @param signature Signature to verify
  215. * @return true if signature is valid, false otherwise
  216. */
  217. bool verifySignature(const std::string& header, const std::string& payload, const std::string& signature) const;
  218. /**
  219. * @brief Split JWT token into parts
  220. *
  221. * @param token JWT token
  222. * @return std::vector<std::string> Token parts (header, payload, signature)
  223. */
  224. static std::vector<std::string> splitToken(const std::string& token);
  225. /**
  226. * @brief Get current timestamp in seconds
  227. *
  228. * @return int64_t Current timestamp
  229. */
  230. static int64_t getCurrentTimestamp();
  231. /**
  232. * @brief Generate random string
  233. *
  234. * @param length Length of the string
  235. * @return std::string Random string
  236. */
  237. static std::string generateRandomString(int length);
  238. };
  239. #endif // JWT_AUTH_H