我试图制作 CLI 工具来访问我的 API。此 API 使用 Express.Js 创建,并使用 Passport.js 进行身份验证,工具将使用 Python 制作。我想问如何使用 csrf 令牌和所有内容验证从 python 的请求库发送的请求。我尝试了简单的身份验证并查看了许多 stackoverflow 答案,但在这种特定情况下没有任何帮助。这是登录表单的样子。
<form action="/login/password" method="post">
<section>
<label for="username">Username</label>
<input id="username" name="username" type="text" autocomplete="username" required autofocus>
</section>
<section>
<label for="current-password">Password</label>
<input id="current-password" name="password" type="password" autocomplete="current-password" required>
</section>
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit">Sign in</button>
这就是上面代码中提到的 `/login/password` 路由的处理方式。
router.post('/login/password', passport.authenticate('local', {
successReturnToOrRedirect: '/',
failureRedirect: '/login',
failureMessage: true
}));
任何和所有的帮助将不胜感激。
所以,当我尝试解决问题而不是在谷歌上寻找解决方案时,我想通了。我使用 BeautifulSoup 从获取 csrf 令牌/login
,然后使用 POST 请求将其发送到/login/password
. 这是代码
def login(session, LOGIN_URL_GET, LOGIN_URL_POST, username, password):
page = session.get(LOGIN_URL_GET)
soup = BeautifulSoup(page.text, "html.parser")
csrf = soup.find('input', {'name': '_csrf'}).get('value')
login_data = dict(username=username, password=password, _csrf=csrf, next='/')
session.post(LOGIN_URL_POST, data=login_data, headers=dict(Referer=LOGIN_URL_GET))
然后我connect.sid
像这样使用 ExpressJS 为会话提供的东西。
with requests.Session() as reqs:
login(reqs, LOGIN_URL_GET, LOGIN_URL_POST, username, password)
connection_sid = reqs.cookies["connect.sid"]
reqs.close()
do_whatever(connection_sid)
编辑:不是 100% 确定connect.sid
,我应该这样做吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句