C++实现基于jwt的token验证
最近做项目遇到一个问题,需要用jwt实现token的验证。首先到jwt的官网查看jwt支持哪些开源库。由于我用的是C++开发的项目,通过比较各个C++开源库,所以最终采用这个开源库实现基于jwt的token验证。采用该开源库主要是因为:1、该开源库支持所有的加密算法,可以参考官网;2、该开源库使用方便。
下面我介绍一下该开源库的使用:
1、该开源库依赖openssl,所以如果你是在win平台编译的程序你可能需要首先安装openssl,至于win下如何安装openssl可以百度,这里不再详细介绍;同时该开源库依赖于C++11,所以win平台下可能需要采用vs2015及以上;
2、不需要编译生成.lib、.dll以及.so文件,使用的时候直接include"base.h jwt.h picojson.h"这三个头文件即可。
下面我介绍一下该开源库的主要接口,方便大家使用。直接上程序:
#include "jwt-cpp/base.h" #include "jwt-cpp/jwt.h" #include "jwt-cpp/picojson.h" #include "iostream" using namespace std; int main(int argc, const char** argv) { std::string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE"; auto decoded = jwt::decode(token); //Get all payload claims for (auto&e1:decoded.get_payload_claims()) std::cout << e1.first << " = " << e1.second.to_json() << std::endl; //Get all header claims for (auto&e2:decoded.get_header_claims()) std::cout << e2.first << " = " << e2.second.to_json() << std::endl; //Create a verifier using the default clock then return verifier instance /* allow_algorithm() Add an algorithm available for checking. param alg Algorithm to allow return *this to allow chaining*/ auto verifier = jwt::verify().allow_algorithm(jwt::algorithm::hs256{"secret"}).with_issuer("auth0"); bool ok = verifier.verify(decoded); printf("ok = %d ", ok); auto token_1 = jwt::create() .set_issuer("auth0") .set_type("JWS") .set_payload_claim("sample", std::string("test")) .sign(jwt::algorithm::hs256{ "secret" }); printf("token_1 = %s ", token_1); }
decode()函数:对你的token进行解码;
get_payload_claims():获取jwt的payload的所有声明,利用std::cout << e1.first << " = " << e1.second.to_json() << std::endl;这句话可以打印输出jwt的负载部分;
get_header_claims():获取jwt的header的所有声明,并同时可以打印输出jwt的头部;
jwt::verify().allow_algorithm(jwt::algorithm::hs256{"secret"}).with_issuer("auth0"):声明一个解码器,利用该解码器可以对你的token值进行验证,hs256是你采用的加密算法,“secret”是你的密钥,这里可以根据自己的实际需求进行更改;
verifier.verify():验证你的token值是否正确。这里我根据自己的实际情况对github上面的开源库做了略微的修改,使其实现:如果token正确的话返回true,token错误返回false;
jwt::create():生成一个token;同时你可以设置token的过期时间,上述程序没有设置token的过期时间。
以上就是主要用到的一些接口的详细介绍。