面试题答案
一键面试JWT存储
在物联网设备网络连接不稳定的情况下,为保证安全认证的可靠性与连续性,JWT可以存储在设备本地的持久化存储中,如文件系统、本地数据库(如SQLite等)。这样即使网络中断,设备仍可使用本地存储的JWT进行认证。
JWT更新
当网络恢复且检测到JWT即将过期或已过期时,设备应向认证服务器请求更新JWT。在请求更新时,设备需携带当前有效的JWT(若未过期),服务器验证后颁发新的JWT。
JWT续期
可以设置一个自动续期机制,在JWT过期前的一定时间(如1/4过期时间),设备自动向服务器发起续期请求。若续期成功,更新本地存储的JWT。
代码示例(以Python为例)
import jwt
import requests
from datetime import datetime, timedelta
# 假设这是设备本地存储JWT的函数
def save_jwt_to_local(jwt_token):
with open('jwt.txt', 'w') as f:
f.write(jwt_token)
# 假设这是从本地读取JWT的函数
def read_jwt_from_local():
try:
with open('jwt.txt', 'r') as f:
return f.read()
except FileNotFoundError:
return None
# 解析JWT获取过期时间
def get_jwt_expiration(jwt_token):
try:
decoded = jwt.decode(jwt_token, options={"verify_signature": False})
return datetime.fromtimestamp(decoded['exp'])
except jwt.PyJWTError:
return None
# 向服务器请求更新JWT
def renew_jwt(current_jwt):
headers = {'Authorization': f'Bearer {current_jwt}'}
response = requests.post('https://your-auth-server.com/renew_jwt', headers=headers)
if response.status_code == 200:
new_jwt = response.json()['new_jwt']
save_jwt_to_local(new_jwt)
return new_jwt
else:
raise Exception('Failed to renew JWT')
# 主逻辑
current_jwt = read_jwt_from_local()
if current_jwt:
expiration = get_jwt_expiration(current_jwt)
if expiration and expiration - datetime.now() < timedelta(hours=1):
new_jwt = renew_jwt(current_jwt)
print('JWT renewed successfully:', new_jwt)
else:
print('No JWT found locally. Need to authenticate first.')
上述代码展示了JWT在本地存储、读取,检查过期时间并在快过期时请求更新的基本流程。实际应用中,需根据具体认证服务器的接口和安全策略进行调整。