OAuth 2.0 和 JWT 授权在 C++ 上的实现:完整代码指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

OAuth 2.0 和 JWT 授权在 C++ 上的实践



现代 Web 应用程序和微服务很少能离开授权系统。两个最流行的标准——用于委托访问的 OAuth 2.0 和用于紧凑数据传输的 JWT(JSON Web Token)——已成为行业事实标准。在本文中,我们将详细讲解如何在 C++ 上实现 OAuth 2.0 客户端以及 JWT 的使用。您将获得现成的代码示例,并了解如何将这些机制集成到您的项目中。



什么是 OAuth 2.0 和 JWT:简要概述



OAuth 2.0 是一种授权协议,它允许应用程序在不传递用户登录名和密码的情况下,获取对用户资源的有限访问权限。主要参与者包括:资源所有者(用户)、客户端(我们的应用程序)、授权服务器(颁发令牌的服务器)和资源服务器(提供数据的服务器)。



JWT 是一种令牌格式,由三部分组成:头部(签名算法)、载荷(数据,例如用户 ID 或角色)和签名(防止篡改的签名)。JWT 通常用作 OAuth 2.0 中的 Bearer 令牌。



在 C++ 中,我们将使用 cpprestsdk 库(用于 HTTP 请求)和 jwt-cpp 库(用于处理 JWT)。通过 vcpkg 安装它们:



vcpkg install cpprestsdkvcpkg install jwt-cpp


在 C++ 上实现 OAuth 2.0 客户端



考虑一个典型场景:我们的 C++ 应用程序需要通过 Google OAuth 2.0 进行授权。为此,我们需要:在 Google Cloud Console 中注册应用程序,获取客户端 ID 和客户端密钥,然后执行授权码流程。



步骤 1:构建授权 URL



第一步是将用户重定向到 Google 的授权页面。使用必要的参数构建 URL:



#include <string>#include <cpprest/http_client.h>#include <cpprest/uri_builder.h>

using namespace web;using namespace web::http;using namespace web::http::client;

std::string BuildAuthorizationUrl(const std::string& client_id, const std::string& redirect_uri, const std::string& state) { uri_builder builder(U("https://accounts.google.com/o/oauth2/v2/auth")); builder.append_query(U("client_id"), utility::conversions::to_string_t(client_id)); builder.append_query(U("redirect_uri"), utility::conversions::to_string_t(redirect_uri)); builder.append_query(U("response_type"), U("code")); builder.append_query(U("scope"), U("openid%20email%20profile")); builder.append_query(U("state"), utility::conversions::to_string_t(state)); builder.append_query(U("access_type"), U("offline")); builder.append_query(U("prompt"), U("consent")); return utility::conversions::to_utf8string(builder.to_uri().to_string());}


步骤 2:用授权码交换令牌



用户确认访问权限后,Google 会将用户重定向到我们的 redirect_uri,并附带参数 code。需要用这个授权码来交换 access_token 和 refresh_token:



pplx::task<web::json::value> ExchangeCodeForToken(    const std::string& client_id,    const std::string& client_secret,    const std::string& redirect_uri,    const std::string& code) {        http_client client(U("https://oauth2.googleapis.com/token"));        web::json::value body;    body[U("code")] = web::json::value::string(utility::conversions::to_string_t(code));    body[U("client_id")] = web::json::value::string(utility::conversions::to_string_t(client_id));    body[U("client_secret")] = web::json::value::string(utility::conversions::to_string_t(client_secret));    body[U("redirect_uri")] = web::json::va                

博客

书籍推荐