从CherryPy中的Ajax Get Request获取登录会话的数据



我正在为一个web应用程序进行身份验证,其中我有以下流程:

登录后,发送POST调用Login方法,如果登录成功则重定向到/user

@cherrypy.expose
def login(self, username=None, password=None):
cursor.execute("""SELECT * FROM Users WHERE username=? and password=?""", (username, password))
result = cursor.fetchone()
if result == None:
sessions[username] = None
raise cherrypy.HTTPRedirect('/')
else:
username = result[0]
sessions[username] = uuid4() 

# Redirects to user page
raise cherrypy.HTTPRedirect('/user/')
然后加载/user页面并在客户端执行以下代码:
$(document).ready(function() {
let username = sessionStorage.getItem('username'); 
var myObject = { "username": username};
$.get("/user/auth", JSON.stringify(myObject),
function(res) {
console.log(res);
});
});

如何从get调用中获得用户名以返回适当的访问令牌?

@cherrypy.expose
def auth(self):
# get username and if login was successful return access token
res = {"authentication": "Ok", "token": uuid4()}
cherrypy.response.headers["Content-Type"] = "application/json"
return json.dumps(res).encode('utf8')

将信息作为参数发送(不需要对js对象进行字符串化):

$(document).ready(function() {
let username = sessionStorage.getItem('username'); 
var myObject = { "username": username};
$.get("/user/auth", myObject,
function(res) {
console.log(res);
});
});

在你的方法中接收参数:

@cherrypy.expose
def auth(self, username):
# get username and if login was successful return access token
res = {"authentication": "Ok", "token": uuid4()}
cherrypy.response.headers["Content-Type"] = "application/json"
return json.dumps(res).encode('utf8')

或者最好使用cherrypy.tools.json_out(不需要直接转换为json或设置内容类型):

@cherrypy.expose
@cherrypy.tools.json_out()
def auth(self, username):
# get username and if login was successful return access token
return {"authentication": "Ok", "token": uuid4()}

最新更新