简体   繁体   中英

How to obtain CSRF token from Laravel and pass it in a python script

I am using oauth2-server-laravel to authenticate an api that exports data to a csv file. The documentation has this requirement.

In order to make some the authorization and resource server work correctly with Laravel5, remove the App\\Http\\Middleware\\VerifyCsrfToken line from the $middleware array and place it in the $routeMiddleware array like this: 'csrf' => App\\Http\\Middleware\\VerifyCsrfToken::class,

Note: remember to add the csrf middleware manually on any route where it's appropriate.

The problem is my application is huge and I would rather not change all my other routes manually. So I came across X-CSRF-TOKEN in the documentation.

My question is: How can I get the csrf token so that I can append it to my header parameter in Python? The docs say I can use the HTML tag meta but I am not using any HTML files for this task.

Also I can't use sessions because I do not need to login to access the API.

A better solution: You can get a token with web scraper easily like BeautifulSoup

import requests
from bs4 import BeautifulSoup

r = requests.get(url) #url is create form 
soup = BeautifulSoup(r.text, 'html.parser')
for link in soup.find_all('input'):
    token = link['value']
   

Of course, note that Laravel also generates a cookie per form. So you need to send cookies along with your post request.

jar = requests.cookies.RequestsCookieJar()
    jar.set('XSRF-TOKEN', r.cookies['XSRF-TOKEN'])

Now you can easily send your post request. For example, I'm sending a request for loggin

url_post = "http://localhost/login"    
data = {
        "_token": token,
        "email": "example@email.com",
        "password": "password"
    }


login_request = requests.post(url_post, data=data, cookies=jar)
print(r.text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM