我正在使用python模块authlib创建flask网站应用程序。我的问题是关于在路由包装中验证收到的JWT的问题。当我验证令牌及其有效载荷时,我不太确定如何确保使用正确的HS256算法对其进行签名,并且没有将其设置为none来完全绕过安全性。我仅通过documentation for JWT prodivded for this library无法理解该如何做 我当前的限制路线换行草稿:
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
token = get_token_auth_header()
claim_options = {
"iss": {
"essential": True,
"values": issuers
},
"aud": {
"essential": True,
"values": audiences
},
"exp": {
"validate": JWTClaims.validate_exp,
},
"sub": {
"essential": True
},
"is_admin": {
"essential": True,
"values": [True,False]
},
"is_moderator": {
"essential": True,
"values": [True,False]
}
}
try:
#TODO set an option here or something to check alg in token?
claims = jwt.decode(token, secret,claims_options=claim_options)
except InvalidTokenError as e:
raise AuthError({"code": "invalid_token",
"description": "token is invalid"}, 401)
except BadSignatureError as e:
raise AuthError({"code": "bad_signature",
"description": "token signature is bad (does not match payload/tampered payload/wrong secret)"}, 401)
except ExpiredTokenError as e:
raise AuthError({"code": "token_expired",
"description": "token is expired"}, 401)
#is this needed or how to do this better with the library used?
if claims.header["alg"] == None or claims.header["alg"] != algorithm:
#prevents auth stripping/setting auth to none attacks and attacks setting from rsa to hs256 and encrypting public key
raise AuthError({"code": "bad_signature",
"description": "signature algorithm given does not match algorithm expected"}, 401)
try:
claims.validate()
return f(*args, **kwargs)
except MissingClaimError as ex:
raise AuthError({"code": "missing_claim",
"description":
"claim is missing"}, 401)
except InvalidClaimError as ex:
raise AuthError({"code": "invalid_claims",
"description":
"incorrect claims,"
"please check the audience and issuer"}, 401)
except ExpiredTokenError as e:
raise AuthError({"code": "token_expired",
"description": "token is expired"}, 401)
return decorated