C++实现基于jwt的token验证

最近做项目遇到一个问题,需要用jwt实现token的验证。首先到jwt的官网https://jwt.io/#libraries查看jwt支持哪些开源库。由于我用的是C++开发的项目,通过比较各个C++开源库,所以最终采用https://github.com/Thalhammer/jwt-cpp这个开源库实现基于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\n", 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\n", 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的过期时间。

以上就是主要用到的一些接口的详细介绍。

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值