一种用以产生访问令牌(token)的开源标准;是目前Token鉴权机制下最流行的方案。?PyJWT是一个Python库,官方文档,
安装如下:pip install pyjwt
JWT编码: 先上一张官方的图
?举个例子:
def encode_token():
payload = {
'exp': datetime.now() + timedelta(minutes=30), # 令牌过期时间
'username': 'BigFish' # 想要传递的信息,如用户名ID
}
key = """{"kty":"RSA","kid":"5995191754202518511","alg":"RS256","n":"lSbCWJdg-73rjKfV5ZijV0dyxZXnH-Ev3eVgkkZbab9xelhTlExdnBKDD1d6F9C_ZkvyV3tOg1tcD27iKZ4WD2Xy6vvUvNj6fxtbcgKOQnW2G5l2aJ69EegXE6RG9yc6EjKX69361t8pZ76MWFQ3BNt-X-6ZqQRJgrzDGD5pTMXHaZceuIIA3blVtBIylKmowt2ug6ieKTMk6CEzdDetBDSeGnXc8vgNQa3TzSvYW4wRVmCIYVby_qKUQqqAnWw1RtrtnLNrp0cJHiCf05g7eRttc4xHA0u4GnhlJEuEVQSr_7DC3tEMcrdH30l_PqO6FHs8DoEn6LrFCsG1oSza2w","e":"AQAB"}"""
encoded_jwt = jwt.encode(payload, key, algorithm='HS256')
print(encoded_jwt)
return encoded_jwt
结果:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDYxNTgzOTIsInVzZXJuYW1lIjoiQmlnRmlzaCJ9.tv__p62tpnmZ7-pYOgmjne8pCZ5Z4WL5juPdC5bseVg
我们在jwt.encode函数中使用了三个参数: 1)第一个是payload,主要用来存放有效的信息,例如用户名,过期时间等想要传递的信息。payload字典内部官方指定有指定key,如exp用来指定token的生命周期。更多指定key参数可参考这里; 2)第二个key,一个秘钥字串,这个秘钥主要用在下文Signature签名中,服务端用来校验Token合法性,这个秘钥仅服务端知道,不能泄露。 3)第三个参数指定Signature签名所用的算法。
编码后的encoded_jwt就是我们要生成的Token。
感兴趣的话,我们进一步来了解下这串字符,观察JWT生成的Token'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MDM5MzA0NzMsInVzZXJuYW1lIjoiQmlnRmlzaCJ9.5eM02YL0xg1DiMZjx-muuYXahTm2etGOEeixFYYd7iI'不难发现这是一条用两个点分割的长字符串,点分割成的三部分是:头信息(header), 消息体(payload)和签名(signature)。
①第一部分是对一个简单js对象的编码后的字符串,这个js对象是用来描述这个token类型以及使用的hash算法,我们对第一部分手动使用base64进行解码base64.b64decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9')会得到b'{"typ":"JWT","alg":"HS256"}'
②第二部分是token的核心,这部分同样是对一个js对象的编码,包含了一些摘要信息。有一些是必须的,有一些是选择性的。base64解码得到b'{"exp":1603930473,"username":"BigFish"}' exp是expires的简写,是用来指定token的生命周期。username是我们选择性添加的用户信息。当然iss也有同等功效(iss是issuer的简写,表明请求的实体,可以是发出请求的用户的信息)更多参数查看文档。
③未签名的令牌由base64url编码的头信息和消息体拼接而成(使用"."分隔),签名(signature)则通过私有的key计算而成 unsignedToken = encodeBase64(header) + '.' + encodeBase64(payload) signature = HMAC-SHA256(key, unsignedToken)
综上,JWT不会对结果进行加密,所以不要保存敏感信息在Header或者Payload中,服务端也主要依靠最后的Signature来验证Token是否有效以及有无被篡改。
jwt 解码:
举个列子:
def decode_token(encoded_jwt):
key = """{"kty":"RSA","kid":"5995191754202518511","alg":"RS256","n":"lSbCWJdg-73rjKfV5ZijV0dyxZXnH-Ev3eVgkkZbab9xelhTlExdnBKDD1d6F9C_ZkvyV3tOg1tcD27iKZ4WD2Xy6vvUvNj6fxtbcgKOQnW2G5l2aJ69EegXE6RG9yc6EjKX69361t8pZ76MWFQ3BNt-X-6ZqQRJgrzDGD5pTMXHaZceuIIA3blVtBIylKmowt2ug6ieKTMk6CEzdDetBDSeGnXc8vgNQa3TzSvYW4wRVmCIYVby_qKUQqqAnWw1RtrtnLNrp0cJHiCf05g7eRttc4xHA0u4GnhlJEuEVQSr_7DC3tEMcrdH30l_PqO6FHs8DoEn6LrFCsG1oSza2w","e":"AQAB"}"""
res = jwt.decode(encoded_jwt, key, algorithms='HS256', options={"verify_signature": False})
print(res)
结果:
{'email': '1323421@qq.com', 'name': 'maice', 'mobile': None, 'externalId': '896937063254116213', 'udAccountUuid': 'd877540a7a77f47296ecff9907943744SkNbxULJm5y', 'ouId': '2320189280760993651', 'ouName': '长三角', 'openId': None, 'idpUsername': 'maice', 'username': 'maice', 'applicationName': '智能选址_规划管理', 'enterpriseId': 'idaas', 'instanceId': 'idaas', 'aliyunDomain': '', 'extendFields': {'themeColor': 'green', 'appName': '智能选址_规划管理'}, 'exp': 1646124276, 'jti': '0gtfWzqLuorG53OcUKYNHA', 'iat': 1646123676, 'nbf': 1646123616, 'sub': 'maice', 'iss': 'http://10.90.5.90/', 'aud': 'idaasplugin_jwt14'}
?
?
总的代码:
import base64
import jwt
from datetime import datetime, timedelta
def encode_token():
payload = {
'exp': datetime.now() + timedelta(minutes=30), # 令牌过期时间
'username': 'BigFish' # 想要传递的信息,如用户名ID
}
key = """{"kty":"RSA","kid":"5995191754202518511","alg":"RS256","n":"lSbCWJdg-73rjKfV5ZijV0dyxZXnH-Ev3eVgkkZbab9xelhTlExdnBKDD1d6F9C_ZkvyV3tOg1tcD27iKZ4WD2Xy6vvUvNj6fxtbcgKOQnW2G5l2aJ69EegXE6RG9yc6EjKX69361t8pZ76MWFQ3BNt-X-6ZqQRJgrzDGD5pTMXHaZceuIIA3blVtBIylKmowt2ug6ieKTMk6CEzdDetBDSeGnXc8vgNQa3TzSvYW4wRVmCIYVby_qKUQqqAnWw1RtrtnLNrp0cJHiCf05g7eRttc4xHA0u4GnhlJEuEVQSr_7DC3tEMcrdH30l_PqO6FHs8DoEn6LrFCsG1oSza2w","e":"AQAB"}"""
encoded_jwt = jwt.encode(payload, key, algorithm='HS256')
print(encoded_jwt)
return encoded_jwt
def decode_token(encoded_jwt):
key = """{"kty":"RSA","kid":"5995191754202518511","alg":"RS256","n":"lSbCWJdg-73rjKfV5ZijV0dyxZXnH-Ev3eVgkkZbab9xelhTlExdnBKDD1d6F9C_ZkvyV3tOg1tcD27iKZ4WD2Xy6vvUvNj6fxtbcgKOQnW2G5l2aJ69EegXE6RG9yc6EjKX69361t8pZ76MWFQ3BNt-X-6ZqQRJgrzDGD5pTMXHaZceuIIA3blVtBIylKmowt2ug6ieKTMk6CEzdDetBDSeGnXc8vgNQa3TzSvYW4wRVmCIYVby_qKUQqqAnWw1RtrtnLNrp0cJHiCf05g7eRttc4xHA0u4GnhlJEuEVQSr_7DC3tEMcrdH30l_PqO6FHs8DoEn6LrFCsG1oSza2w","e":"AQAB"}"""
res = jwt.decode(encoded_jwt, key, algorithms='HS256', options={"verify_signature": False})
print(res)
def test_decode():
header = base64.b64decode('eyJhbGciOiJSUzI1NiIsImtpZCI6IjU5OTUxOTE3NTQyMDI1MTg1MTEifQ')
payload = base64.b64decode(
'eyJlbWFpbCI6IjEzMjM0MjFAcXEuY29tIiwibmFtZSI6Im1haWNlIiwibW9iaWxlIjpudWxsLCJleHRlcm5hbElkIjoiODk2OTM3MDYzMjU0MTE2MjEzIiwidWRBY2NvdW50VXVpZCI6ImQ4Nzc1NDBhN2E3N2Y0NzI5NmVjZmY5OTA3OTQzNzQ0U2tOYnhVTEptNXkiLCJvdUlkIjoiMjMyMDE4OTI4MDc2MDk5MzY1MSIsIm91TmFtZSI6IumVv-S4ieinkiIsIm9wZW5JZCI6bnVsbCwiaWRwVXNlcm5hbWUiOiJtYWljZSIsInVzZXJuYW1lIjoibWFpY2UiLCJhcHBsaWNhdGlvbk5hbWUiOiLmmbrog73pgInlnYBf6KeE5YiS566h55CGIiwiZW50ZXJwcmlzZUlkIjoiaWRhYXMiLCJpbnN0YW5jZUlkIjoiaWRhYXMiLCJhbGl5dW5Eb21haW4iOiIiLCJleHRlbmRGaWVsZHMiOnsidGhlbWVDb2xvciI6ImdyZWVuIiwiYXBwTmFtZSI6IuaZuuiDvemAieWdgF_op4TliJLnrqHnkIYifSwiZXhwIjoxNjQ2MTI0Mjc2LCJqdGkiOiIwZ3RmV3pxTHVvckc1M09jVUtZTkhBIiwiaWF0IjoxNjQ2MTIzNjc2LCJuYmYiOjE2NDYxMjM2MTYsInN1YiI6Im1haWNlIiwiaXNzIjoiaHR0cDovLzEwLjkwLjUuOTAvIiwiYXVkIjoiaWRhYXNwbHVnaW5fand0MTQifQ')
# unsignedToken = encodeBase64(header) + '.' + encodeBase64(payload)
# signature = HMAC - SHA256(key, unsignedToken)
print(header)
print(payload)
if __name__ == '__main__':
encoded_jwt = encode_token()
encoded_jwt = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjU5OTUxOTE3NTQyMDI1MTg1MTEifQ.eyJlbWFpbCI6IjEzMjM0MjFAcXEuY29tIiwibmFtZSI6Im1haWNlIiwibW9iaWxlIjpudWxsLCJleHRlcm5hbElkIjoiODk2OTM3MDYzMjU0MTE2MjEzIiwidWRBY2NvdW50VXVpZCI6ImQ4Nzc1NDBhN2E3N2Y0NzI5NmVjZmY5OTA3OTQzNzQ0U2tOYnhVTEptNXkiLCJvdUlkIjoiMjMyMDE4OTI4MDc2MDk5MzY1MSIsIm91TmFtZSI6IumVv-S4ieinkiIsIm9wZW5JZCI6bnVsbCwiaWRwVXNlcm5hbWUiOiJtYWljZSIsInVzZXJuYW1lIjoibWFpY2UiLCJhcHBsaWNhdGlvbk5hbWUiOiLmmbrog73pgInlnYBf6KeE5YiS566h55CGIiwiZW50ZXJwcmlzZUlkIjoiaWRhYXMiLCJpbnN0YW5jZUlkIjoiaWRhYXMiLCJhbGl5dW5Eb21haW4iOiIiLCJleHRlbmRGaWVsZHMiOnsidGhlbWVDb2xvciI6ImdyZWVuIiwiYXBwTmFtZSI6IuaZuuiDvemAieWdgF_op4TliJLnrqHnkIYifSwiZXhwIjoxNjQ2MTI0Mjc2LCJqdGkiOiIwZ3RmV3pxTHVvckc1M09jVUtZTkhBIiwiaWF0IjoxNjQ2MTIzNjc2LCJuYmYiOjE2NDYxMjM2MTYsInN1YiI6Im1haWNlIiwiaXNzIjoiaHR0cDovLzEwLjkwLjUuOTAvIiwiYXVkIjoiaWRhYXNwbHVnaW5fand0MTQifQ.CddyMl_q9eK1Mfid-gYilJ43D-wMcyNW3GliTZh6JrFKFn8pHsVwnsYxDFlk93vcp7tK3_HyGCSV99AfF8LKj9q1VE3B83q9fcTK8pyc67EJJDonRRuYXbx82_34V5N3UhZBHAxhrIwmO943GeHuobBumXSfTtKhiX-VJ1taPQDMJvMDGbe-wCHJws18NZypjFYccoZjvc-Biy8z7y-ST0dit_TiwGDSNvDd5I1hSxGtcfUtkUIRuaO6xRZ6KC_PTvD_J5-jmHOjpLjp99rIHpS3FLhHmDKHPzDDiAgHUrel1hp6ZMmldWA27HjuUNZs8gVngZJXJ92sKY3d0btRDQ"
decode_token(encoded_jwt)
# test_decode()
|