简体   繁体   中英

How to catch jwt ExpiredSignatureError exception in python using try and except blocks

Instead of printing jwt.exceptions.ExpiredSignatureError jwt.exceptions.ExpiredSignatureError: Signature has expired

I want to print a message that print("Token has expired") when they click on the URL sent to the mail

I have already tried code which returns to the page even if it is expired

@mod.route('/forgot/<token>', methods=['GET', 'POST'])
    def get_resetpassword(token):
result = ''
errorMsg = None
try:
    token_decode = jwt.decode(token, app.config['SECRET KEY'], 'exp', algorithm='HS256')
    print(str(token_decode))
except jwt.ExpiredSignature:
    print("Invalid Token")
    if request.method == 'POST':
        if request.form['password'] != '':
            return redirect('/company/admin')
        else:
            errorMsg= 'Please Enter Password '
    return render_template('reset_token.html',error=errorMsg)

The below code executes properly without try and Except block

@mod.route('/forgot/<token>', methods=['GET', 'POST'])
def get_resetpassword(token):
result = ''
errorMsg = None
token_decode = jwt.decode(token, app.config['SECRET KEY'], 'exp', algorithm='HS256')
print(str(token_decode))

if request.method == 'POST':
    if request.form['password'] != '':
        return redirect('/company/admin')
    else:
        errorMsg= 'Please Enter Password '
return render_template('reset_token.html',error=errorMsg)

I want to insert try and except block to my code

@mod.route('/forgot/<token>', methods=['GET', 'POST'])
def get_resetpassword(token):
    result = ''
    errorMsg = None
    try:
        token_decode = jwt.decode(token, app.config['SECRET KEY'], 'exp', algorithm='HS256')
        print(str(token_decode))
        if request.method == 'POST':
            if request.form['password'] != '':
                return redirect('/company/admin')
            else:
                errorMsg= 'Please Enter Password '
        return render_template('reset_token.html',error=errorMsg)
    except jwt.ExpiredSignature:
        print("Invalid Token")

Just place an except block at the right spot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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