如何使用cURL发送Cookie?

w9apscun  于 2023-02-23  发布在  其他
关注(0)|答案(9)|浏览(166)

我读到sending cookies with cURL工作,但不适合我。
我有一个REST端点,如下所示:

class LoginResource(restful.Resource):
    def get(self):
        print(session)
        if 'USER_TOKEN' in session:
            return 'OK'
        return 'not authorized', 401

当我尝试访问端点时,它拒绝:

curl -v -b ~/Downloads/cookies.txt -c ~/Downloads/cookies.txt http://127.0.0.1:5000/
* About to connect() to 127.0.0.1 port 5000 (#0)
*   Trying 127.0.0.1...
* connected
* Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.27.0
> Host: 127.0.0.1:5000
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 401 UNAUTHORIZED
< Content-Type: application/json
< Content-Length: 16
< Server: Werkzeug/0.8.3 Python/2.7.2
< Date: Sun, 14 Apr 2013 04:45:45 GMT
<
* Closing connection #0
"not authorized"%

其中我的~/Downloads/cookies.txt是:

cat ~/Downloads/cookies.txt
USER_TOKEN=in

并且服务器什么也不接收:

127.0.0.1 - - [13/Apr/2013 21:43:52] "GET / HTTP/1.1" 401 -
127.0.0.1 - - [13/Apr/2013 21:45:30] "GET / HTTP/1.1" 401 -
<SecureCookieSession {}>
<SecureCookieSession {}>
127.0.0.1 - - [13/Apr/2013 21:45:45] "GET / HTTP/1.1" 401 -

我错过了什么?

s6fujrry

s6fujrry1#

这对我很有效:

curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/

我可以看到后端使用的价值

print(request.cookies)
r55awzrz

r55awzrz2#

你可以参考https://curl.haxx.se/docs/http-cookies.html来获得如何使用cookies的完整教程。

curl -c /path/to/cookiefile http://yourhost/

写入cookie文件并启动引擎,以及使用您可以使用的cookie

curl -b /path/to/cookiefile  http://yourhost/

读取cookie并启动cookie引擎,或者如果它不是文件,它将传递给定的字符串。

pbwdgjma

pbwdgjma3#

您在cookie文件中使用了错误的格式。如curl documentation所述,它使用的是旧的Netscape cookie文件格式,与Web浏览器使用的格式不同。如果您需要手动创建curl cookie文件,this post可以帮助您。在您的示例中,该文件应包含以下行

127.0.0.1   FALSE   /   FALSE   0   USER_TOKEN  in

具有7个TAB分隔的字段,表示 * 域 尾匹配 路径 安全 过期 名称 值 *。

xa9qqrwz

xa9qqrwz4#

curl -H @<header_file> <host>
由于@<file>支持来自文件的curl 7.55标头
echo 'Cookie: USER_TOKEN=Yes' > /tmp/cookie
curl -H @/tmp/cookie <host>
文档和提交

6ie5vjzr

6ie5vjzr5#

如果您已经在应用中发出了该请求,并在Google Dev Tools中看到了该请求,则可以在网络选项卡中右键单击该请求时使用上下文菜单中的复制cURL命令。复制-〉复制为cURL。它将包含所有头部、Cookie等。

btxsgosb

btxsgosb6#

我用的是Debian,但是我不能用波浪号作为路径。最初我用的是

curl -c "~/cookie" http://localhost:5000/login -d username=myname password=mypassword

我不得不将其更改为:

curl -c "/tmp/cookie" http://localhost:5000/login -d username=myname password=mypassword

-c创建cookie,-b使用cookie
所以我会用这个例子:

curl -b "/tmp/cookie" http://localhost:5000/getData
hpcdzsge

hpcdzsge7#

另一个使用json的解决方案。
curl :

curl -c /tmp/cookie -X POST -d '{"chave":"email","valor":"hvescovi@hotmail.com"}' -H "Content-Type:application/json" localhost:5000/set

curl -b "/tmp/cookie" -d '{"chave":"email"}' -X GET -H "Content-Type:application/json"  localhost:5000/get

curl -b "/tmp/cookie" -d '{"chave":"email"}' -X GET -H "Content-Type:application/json" localhost:5000/delete

PYTHON代码:

from flask import Flask, request, session, jsonify
from flask_session import Session

app = Flask(__name__)

app.secret_key = '$#EWFGHJUI*&DEGBHYJU&Y%T#RYJHG%##RU&U'
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

@app.route('/')
def padrao():
    return 'backend server-side.'
    
@app.route('/set', methods=['POST'])
def set():
    resposta = jsonify({"resultado": "ok", "detalhes": "ok"})
    dados = request.get_json()  
    try:  
        if 'chave' not in dados: # não tem o atributo chave?
            resposta = jsonify({"resultado": "erro", 
                            "detalhes": "Atributo chave não encontrado"})
        else:
            session[dados['chave']] = dados['valor']
    except Exception as e:  # em caso de erro...
        resposta = jsonify({"resultado": "erro", "detalhes": str(e)})

    resposta.headers.add("Access-Control-Allow-Origin", "*")
    return resposta  

@app.route('/get')
def get():
    try:
        dados = request.get_json()  
        retorno = {'resultado': 'ok'}
        retorno.update({'detalhes': session[dados['chave']]}) 
        resposta = jsonify(retorno)
    except Exception as e:  
        resposta = jsonify({"resultado": "erro", "detalhes": str(e)})
    
    resposta.headers.add("Access-Control-Allow-Origin", "*")
    return resposta 

@app.route('/delete')
def delete():
    try:
        dados = request.get_json()  
        session.pop(dados['chave'], default=None)
        resposta = jsonify({"resultado": "ok", "detalhes": "ok"})        
    except Exception as e:  # em caso de erro...
        resposta = jsonify({"resultado": "erro", "detalhes": str(e)})
            
    resposta.headers.add("Access-Control-Allow-Origin", "*")
    return resposta  

app.run(debug=True)
krcsximq

krcsximq8#

以下是发送Cookie的正确方法示例。-H 'cookie: key1=val2; key2=val2;'
cURL也提供了--cookie的便利。
这是从Chrome浏览器〉检查〉网络〉复制为cURL。

curl 'https://www.example.com/api/app/job-status/' \
  -H 'authority: www.example.com' \
  -H 'sec-ch-ua: "Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.111.111 Safari/111.36' \
  -H 'content-type: application/json' \
  -H 'accept: */*' \
  -H 'origin: https://www.example.com' \
  -H 'sec-fetch-site: same-origin' \
  -H 'sec-fetch-mode: cors' \
  -H 'sec-fetch-dest: empty' \
  -H 'referer: https://www.example.com/app/jobs/11111111/' \
  -H 'accept-language: en-US,en;q=0.9' \
  -H 'cookie: menuOpen_v3=true; imageSize=medium;' \
  --data-raw '{"jobIds":["1111111111111"]}' \
  --compressed
bgtovc5b

bgtovc5b9#

我在Windows上使用GitBash,但没有找到任何适合我的。
所以我决定将我的cookie保存到一个名为.session的文件中,并使用cat读取它,如下所示:

curl -b $(cat .session) http://httpbin.org/cookies

如果你好奇的话,我的饼干是这样的:

session=abc123

相关问题