我撰寫了一個非常原始的 C HTTP 服務器,我想使用 JWT-CPP 支持 JWT 令牌。基本上,我有 2 個端點:
- 如果請求是 /auth/username,我將使用 URL 中給出的用戶名生成 JWT 令牌。
- 如果請求是 /verify,我將檢查請求標頭中的 Cookie 并查找 JWT 令牌。如果存在,我將對其進行驗證并在 JWT 有效負載中回傳用戶名。
這是我發送回應的部分代碼:
// Check and give JWT token
if (has_auth == 0 || auth_right == 0) {
// HTTPGET[1] contains the URL requested. For example, 'auth/username'
size_t pos1 = HTTPGET[1].find('/');
size_t pos2 = HTTPGET[1].find('/', pos1 1);
std::string mode = HTTPGET[1].substr(0, pos2);
printf("JWT: mode is: %s\n", mode.c_str());
if (strcmp(mode.c_str(), "/auth") == 0) {
printf("JWT: Auth\n");
size_t pos3 = HTTPGET[1].find('/', pos2 1);
std::string username = HTTPGET[1].substr(pos2 1, pos3);
printf("JWT: username is: %s\n", username.c_str());
auto token = jwt::create()
.set_issuer("auth0")
.set_type("JWS")
.set_payload_claim("sub", jwt::claim(username))
.set_issued_at(std::chrono::system_clock::now())
.set_expires_at(std::chrono::system_clock::now() std::chrono::seconds{86400})
.sign(jwt::algorithm::hs256{"secret"});
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::hs256{ "secret" })
.with_issuer("auth0");
auto decode = jwt::decode(token);
std::string GiveJWT = "HTTP/1.1 200 OK\r\nServer: myhttpserver\r\n" CORS_header "Content-type: text/plain\r\nSet-Cookie: token=" token
"\r\n\r\n JWT token generated successful!\nYour token's username is: " username "\n";
write(fd, GiveJWT.c_str(), GiveJWT.size());
return;
}
//return;
} else {
std::string NeedAuth = "HTTP/1.1 401 Unauthorized\r\nServer: myhttpserver\r\n" CORS_header "Content-type: text/plain\r\n\r\nAuthorization failed\n";
write(fd, NeedAuth.c_str(), NeedAuth.size());
}
// Verify user's token
// rel_path contains the url or subdomain of the request. For example, the url here should be './verify'.
if (strcmp(rel_path.c_str(), "./verify") == 0) {
printf("Get in the verify\n");
if (auth_right == 1) {
auto decode = jwt::decode(success_token);
std::string username = decode.get_payload_claim("sub").as_string();
printf("username is: %s\n", decode.get_payload_claim("sub").as_string());
std::string JWTConfirm = "HTTP/1.1 200 OK\r\nServer: myhttpserver\r\n" CORS_header "Content-type: text/plain\r\n\r\nYour user name is: ?" username "\n";
write(fd, JWTConfirm.c_str(), JWTConfirm.size());
return;
} else {
std::string JWTConfirm = "HTTP/1.1 401 Unauthorized\r\nServer: myhttpserver\r\n" CORS_header "Content-type: text/plain\r\n\r\nWhate are you looking at?";
write(fd, JWTConfirm.c_str(), JWTConfirm.size());
return;
}
}
這是我通過訪問 /auth/oreo 得到的 HTTP 標頭和回應:

我可以看到服務器在其標頭中支持 CORS,因此 cookie 應該能夠跨域傳輸。但是,如果我切換到端點 /verify,則不會攜帶該令牌 cookie。我知道 Cookie 應該是基于會話的,但是只要瀏覽器會話存在,我是否可以攜帶這個 cookie?
uj5u.com熱心網友回復:
很抱歉前面的誤解。我的意思是不同的路徑,而不是不同的子域。最后,我通過在我的 Cookie 后添加“Path=/”屬性解決了這個問題,這允許 cookie 跨不同路徑進行傳遞。
但是,如果您之前存盤過舊 cookie,請確保先清除它們。這可能是我的端點的問題,但如果我不清除 cookie,即使我關閉服務器端的套接字,請求也會神秘地掛起。我不確定為什么。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/408564.html
標籤:
