2

我用 python 模块authlib创建了一个烧瓶网络应用程序。我的问题是关于在路由包装器中验证收到的 JWT。当我验证令牌及其有效负载时,我不太确定如何确保它使用正确的 HS256 算法进行签名,并且没有设置为 none 以完全绕过安全性。仅从为该库提供的 JWT 文档中我无法理解如何执行此操作 我当前的受限路由包装草稿:

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
4

0 回答 0