flask 如何跳转到第三方页面, 要 post 数据.

2020-01-03 13:12:27 +08:00
 l4ever
用 redirect 只能跳转, 但是无法 post 数据过去啊.
2978 次点击
所在节点    Python
16 条回复
bolide2005
2020-01-03 13:19:12 +08:00
还是再详细描述一下你的场景吧。

redirect 而又携带原方法的,我记得是用状态码 307 实现的,不过一般的 web framework 都不这么做(?),你要非得用的话估计得自己制定状态码,这还要看第三方服务支持不支持 307。

而且 redirect 又 post,这是一种什么场景呢?
bolide2005
2020-01-03 13:21:27 +08:00
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307

"The only difference between 307 and 302 is that 307 guarantees that the method and the body will not be changed when the redirected request is made. With 302, some old clients were incorrectly changing the method to GET: the behavior with non-GET methods and 302 is then unpredictable on the Web, whereas the behavior with 307 is predictable. For GET requests, their behavior is identical."

注意看这里的 302 和 307 的区别
l4ever
2020-01-03 13:24:04 +08:00
@bolide2005 我是想通过访问一个 flask 写的页面生成一段 token, 通过 token 登录第三方网站.
我首先想到的是 redirect('http://xxx.com/login/?token=xxxxx')
这是 get 当然可以

但是如果是 post, 第三方网站只能 post 请求
如何把我的 tokenpost 到 http://xxx.com/login/ 并跳转.实现登录
bolide2005
2020-01-03 13:26:46 +08:00
@l4ever #3
redirect 的方法有一个参数 code 是用来制定状态码的,传入 307 试试?
不过你这种用法又不一样了,相当于又修改了 browser 传入的 body,能不能行我就不确定了,可以自己起个服务测测
bolide2005
2020-01-03 13:27:10 +08:00
制定 -> 指定
bolide2005
2020-01-03 13:29:18 +08:00
我想了想,八成是不行的。

redirect 其实是通过状态码要求 browser 进行某种重新请求,你修改的 body 是没办法传给 browser 的,这条路估计走不通。
l4ever
2020-01-03 13:30:44 +08:00
@bolide2005 redirect 应该做不到. 不知道 flask 有没有其他的方法能做到.
l4ever
2020-01-03 13:32:43 +08:00
我想了一下, 跳到自己的页面. 用 js 提交这个 form 可以做到. 但这样太不科学了.
jowan
2020-01-03 13:32:53 +08:00
用 flash 生成 form 表单自动提交过去就行了 参考支付宝的 SDK
jowan
2020-01-03 13:33:56 +08:00
你下载支付宝网页支付的 SDK 就知道了 他自己就是生成 form 表单跳转过去的
你 flask 也可以在 template 里面生成表单自动提交
bolide2005
2020-01-03 13:34:02 +08:00
@l4ever #8
第三方是自己的服务吗?
如果不是的话你这样做会遇到跨域的问题。
leishi1313
2020-01-03 14:12:28 +08:00
做不到的,你要登录第三方人家凭什么让你一个 token 就能登上。你要是 redirect 到第三方登录页然后用户名 /密码自动填充还差不多
ipwx
2020-01-03 14:15:10 +08:00
如果第三方页面不是你控制的,一个 csrf token 就能让你无法可行
l4ever
2020-01-03 14:36:00 +08:00
```
return f"""
<title>LOADING</title>
<body onload="document.forms[0].submit();">
<form id="sso" action="xxx.com" method="POST">
<input type="hidden" value="{token}">
</body>
"""
```
可以了.
l4ever
2020-01-03 14:36:20 +08:00
@leishi1313
@ipwx 本帖不讨论安全
Lax
2020-01-03 15:06:44 +08:00
用脚本 form.submit 吧。在浏览器发生的跳转,POST 又注定不能用 redirect 和 location.href。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/634742

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX