【发布时间】:2020-12-12 05:20:00
【问题描述】:
我目前正在开发一个使用 JWT 和 python 创建安全登录的项目。这是一个简单的银行账户应用程序,显示用户名、出生日期和账户余额。在我的代码中,我仍然可以通过更改分配给其他用户的 URL 帐号(例如 www.domain.com/account/#)来访问其他帐户。
如果 foo 是帐户 16 并且已登录,我可以将数字更改为 17,从而允许我访问 bar 的帐户,并提供他们的信息,这是一个很大的禁忌。我只想只能看到foo自己的账户信息。我正在尝试检查 JWT 以确保 foo 是用户,并且在将数据发送给用户之前它是 foo 的帐户信息。
传递给函数的 JWT 包含经过身份验证的用户的 username 和 logged_in 字段(或声明)。我正在尝试通过 URL 中的数字与正在数据库中查找的帐户进行比较。我还试图确保如果 JWT 中的用户名与从数据库返回的用户名不匹配,则引发“您无权访问”异常。
我一直在拼命想办法解决这个问题。
有效载荷
jwt_token = {
"username": "foo",
"logged_in": true
}
代码
import jwt
import pymysql
class LoggedOutException(Exception):
'''Raising a LoggedOutException will redirect the user to the login screen
in the app.
'''
pass
def account_lookup(account_id, jwt_token):
try:
token = jwt.decode(jwt_token, 'secret', algorithm='HS256')
except Exception as e:
raise LoggedOutException('User is not logged in')
if "logged_in" in token.keys() and token["logged_in"] == True:
conn = pymysql.connect(
host='mysql',
port=3306,
user='root',
passwd='letmein',
db='BankApp'
)
cursor = conn.cursor()
statement = "SELECT username FROM tbl_user WHERE id = " + account_id + ";"
cursor.execute(statement)
username_results = cursor.fetchone()
if username_results:
username = username_results[0]
statement = "SELECT balance, dob FROM tbl_account WHERE user_id = " + account_id + ";"
cursor.execute(statement)
account_results = cursor.fetchone()
conn.commit()
cursor.close()
conn.close()
return {
'balance': account_results[0],
'dob': account_results[1],
'username': username
}
else:
raise Exception('Account not found')
else:
raise LoggedOutException('User is not logged in')
【问题讨论】: