添加JWT功能,包括创建、获取和验证令牌的实现
This commit is contained in:
parent
7ef304a909
commit
d3efc643f5
19
include/jwt/jwt.h
Normal file
19
include/jwt/jwt.h
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
#ifndef JWT_H
|
||||||
|
#define JWT_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C"
|
||||||
|
{
|
||||||
|
#endif
|
||||||
|
|
||||||
|
char* create_token(const char* user, const char* secret);
|
||||||
|
|
||||||
|
char* get_payload(const char* token);
|
||||||
|
|
||||||
|
int verify_token(const char* token, const char* secret);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif // JWT_H
|
@ -1,5 +1,5 @@
|
|||||||
#ifndef KQM_TYPES_H
|
#ifndef SERVER_TYPES_H
|
||||||
#define KQM_TYPES_H
|
#define SERVER_TYPES_H
|
||||||
|
|
||||||
#include <civetweb.h>
|
#include <civetweb.h>
|
||||||
|
|
||||||
@ -8,4 +8,4 @@ typedef struct mg_context mg_context;
|
|||||||
typedef struct mg_connection mg_connection;
|
typedef struct mg_connection mg_connection;
|
||||||
typedef struct mg_request_info mg_request_info;
|
typedef struct mg_request_info mg_request_info;
|
||||||
|
|
||||||
#endif // KQM_TYPES_H
|
#endif // SERVER_TYPES_H
|
46
src/jwt/jwt.cpp
Normal file
46
src/jwt/jwt.cpp
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
#include "jwt.h"
|
||||||
|
|
||||||
|
#include <chrono>
|
||||||
|
#include <jwt-cpp/jwt.h>
|
||||||
|
|
||||||
|
|
||||||
|
using namespace std::literals::chrono_literals;
|
||||||
|
|
||||||
|
extern "C"
|
||||||
|
{
|
||||||
|
char* create_token(const char* user_id, const char* secret)
|
||||||
|
{
|
||||||
|
auto token = jwt::create()
|
||||||
|
.set_type("JWS")
|
||||||
|
.set_issuer("KeqingMoe")
|
||||||
|
.set_subject("user_id")
|
||||||
|
.set_audience("web_client")
|
||||||
|
.set_expires_at(std::chrono::system_clock::now() + 3s)
|
||||||
|
.set_payload_claim("user_id", jwt::claim(std::string{user_id}))
|
||||||
|
.sign(jwt::algorithm::hs256{secret});
|
||||||
|
return strdup(token.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
char* get_payload(const char* token)
|
||||||
|
{
|
||||||
|
auto decoded_token = jwt::decode(token);
|
||||||
|
auto payload = decoded_token.get_payload_claim("user_id").as_string();
|
||||||
|
return strdup(payload.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
int verify_token(const char* token, const char* secret)
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
auto decoded_token = jwt::decode(token);
|
||||||
|
|
||||||
|
auto verifier = jwt::verify()
|
||||||
|
.allow_algorithm(jwt::algorithm::hs256{secret})
|
||||||
|
.with_issuer("KeqingMoe")
|
||||||
|
.with_subject("user_id");
|
||||||
|
verifier.verify(decoded_token);
|
||||||
|
return 1;
|
||||||
|
} catch (...) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user