简体   繁体   English

如何在python中编码JWT

[英]How to encode a JWT in python

In an attempt to create a JWT in python I have written the following code.为了在 python 中创建 JWT,我编写了以下代码。

#Header
header = str({"alg": "RS256"})
header_binary = header.encode()
header_base64 = base64.urlsafe_b64encode(header_binary)
print(header_base64)

#Claims set (Pay Load)
client_id="" 
username="" 
URL=""
exp_time=str(round(time.time())+300) 
claims = str({"iss": client_id,
      "sub": username,
      "aud": URL,
      "exp": exp_time})
claims_binary = claims.encode()
claims_base64 = base64.urlsafe_b64encode(claims_binary)
print(claims_base64)

I understand there is still more to do but I have the following problem.我知道还有更多工作要做,但我有以下问题。 If I concatenate the two strings created above with a "."如果我用“.”连接上面创建的两个字符串。 and put the resulting string in a JWT debugger it seems the claims set works perfectly but the same cannot be said for the header.并将结果字符串放入 JWT 调试器中,看起来声明集工作得很好,但对于标头却不能这样说。

Please advise if this is the correct way to go about doing this and what my errors are.请告知这是否是执行此操作的正确方法以及我的错误是什么。

Python has a good module already created for this called, PyJWT . Python 已经为此创建了一个很好的模块,称为PyJWT Try using that instead of following such a long process.尝试使用它而不是遵循如此漫长的过程。

Also, it would allow you to use multiple algorithms to encode your data into, and other multiple features too.此外,它还允许您使用多种算法将数据编码为其他多种功能。

Can you use third-party libraries?可以使用第三方库吗? If so take a look at the docs如果是这样,请查看文档

Example:例子:

import jwt

... # Define your payload variables

# Encode JWT
encoded_jwt = jwt.encode({"iss": client_id,
      "sub": username,
      "aud": URL,
      "exp": exp_time},
      'secret', algorithm='HS256')

# Decode JWT
decoded_jwt = jwt.decode(encoded_jwt, 'secret', algorithms=['HS256'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM