Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to Fetch Time from Web Server using Python Requests Library (Status Code 401)

I’m currently working on a Python script that continuously fetches the current time from a web server and prints it. However, I’m encountering an issue with the authentication, resulting in a 401 status code. I’ve provided all the necessary headers and access token, but the response indicates an authentication problem. The web server’s link: http://cyber.cs.du.edu/timekeeper/ (This is a hypothetical website made by my University just for the purpose of this assignment)

from datetime import datetime
import time

def get_current_time():
    try:
        time_api_url = "http://cyber.cs.du.edu/timekeeper/api/v1/time"
        headers = {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpcCI6IjE3Mi4xNy4wLjEiLCJybmQiOiIxMWEzN2Q1YTQ3ZTQxY2ViNzMwZWEyNDg5N2MzOWMwZTUwM2QzNDU1NGQ5MjFjNmE0NGY2NGJlMDI5OTkxYTU5IiwiYWdlbnQiOiJNb3ppbGxhLzUuMCAoTWFjaW50b3NoOyBJbnRlbCBNYWMgT1MgWCAxMF8xNV83KSBBcHBsZVdlYktpdC81MzcuMzYgKEtIVE1MLCBsaWtlIEdlY2tvKSBDaHJvbWUvMTE5LjAuMC4wIFNhZmFyaS81MzcuMzYiLCJleHAiOjE2OTk1NTM4NTJ9.fFIpbEmAhotro4MgL0GTSbYrtl--t92MTFKnNX-tnfw',
            'Connection': 'keep-alive',
            'Cookie': '_cap=344691521684862355; _fbp=fb.1.1684862355417.17791420; _attrb=%22293b6266-57cb-4269-93ef-a6308b74f593%22; _scid=8509b8d8-90ea-4e40-840d-6f19637fbe27; _ga_S2V8B3QG10=GS1.2.1693412411.17.0.1693412411.0.0.0; _gcl_au=1.1.1900453194.1694548891; _ga_EQYTG2FRZB=GS1.1.1694643835.4.1.1694643921.0.0.0; _ga_3R9779E9CE=GS1.1.1697141496.2.1.1697141511.0.0.0; _ga_YD6NSK449L=GS1.1.1698702601.3.0.1698702602.59.0.0; _ga_G3QL5ZJ7V2=GS1.1.1698706614.2.1.1698706721.60.0.0; cebs=1; _gid=GA1.2.7375447.1699384534; _ga_KDCJP7WQR2=GS1.2.1699384534.32.1.1699384541.0.0.0; _sctr=1%7C1699340400000; cebsp_=3; _scid_r=8509b8d8-90ea-4e40-840d-6f19637fbe27; _ce.s=v~cdafb05ef8918fcf3bc3bb022cd2ae51233ea0de~lcw~1699393884317~vpv~3~v11.cs~348336~v11.s~690beb20-7db7-11ee-8ffb-e3470a664e62~v11.sla~1699393884364~gtrk.la~loov8lm7~v11.send~1699393884316~lcw~1699393884366; _ga_7KPJG812Y3=GS1.1.1699394129.1.1.1699394621.0.0.0; _ga=GA1.2.1823087093.1684861047; _ga_CMGRJVENZ2=GS1.1.1699484166.33.0.1699484166.60.0.0; _ga_0F4BY0DEFX=GS1.1.1699484166.5.0.1699484166.0.0.0; _ga_RPN0H7RH0P=GS1.2.1699484369.203.1.1699484382.0.0.0; bt=1699553552.3100853; _acdk=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0cyI6MTY5OTU1MzU1MiwiZXhwIjoxNjk5NTUzNTYyLCJ0b2tlbiI6ImV5SmhiR2NpT2lKSVV6STFOaUlzSW5SNWNDSTZJa3BYVkNKOS5leUpwY0NJNklqRTNNaTR4Tnk0d0xqRWlMQ0p5Ym1RaU9pSXhNV0V6TjJRMVlUUTNaVFF4WTJWaU56TXdaV0V5TkRnNU4yTXpPV013WlRVd00yUXpORFUxTkdRNU1qRmpObUUwTkdZMk5HSmxNREk1T1RreFlUVTVJaXdpWVdkbGJuUWlPaUpOYjNwcGJHeGhMelV1TUNBb1RXRmphVzUwYjNOb095QkpiblJsYkNCTllXTWdUMU1nV0NBeE1GOHhOVjgzS1NCQmNIQnNaVmRsWWt0cGRDODFNemN1TXpZZ0tFdElWRTFNTENCc2FXdGxJRWRsWTJ0dktTQkRhSEp2YldVdk1URTVMakF1TUM0d0lGTmhabUZ5YVM4MU16Y3VNellpTENKbGVIQWlPakUyT1RrMU5UTTROVEo5LmZGSXBiRW1BaG90cm80TWdMMEdUU2JZcnRsLS10OTJNVEZLbk5YLXRuZncifQ.lkFT0blGLG50DJy_jfQUFuUdHDhnId1WBBk68vIQbeM',
            'Host': 'cyber.cs.du.edu',
            'Referer': 'http://cyber.cs.du.edu/timekeeper/',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest',
            'X-Timekeeper-Channel': 'Web'
        }

        response = requests.get(time_api_url, headers=headers)

        print(response)

        if response.status_code == 200:
            try:
                current_time = response.json().get('current_time')
                formatted_time = datetime.utcfromtimestamp(current_time).strftime('%Y-%m-%d %H:%M:%S')
                print(formatted_time)
            except ValueError:
                print("Invalid JSON response")

        else:
            print(f"Error: {response.text}")

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    try:
        while True:
            get_current_time()
            time.sleep(1)  # Adjust the sleep interval as needed
    except KeyboardInterrupt:
        print("Script stopped.")

I’m using the Python requests library to make a GET request to a time API.
I’ve included the necessary headers, and I’m sure the access token and cookies are correct.
However, I’m consistently getting a 401 status code with the error "Unauthorized."

I’ve double-checked the access token and cookies for correctness and I’ve ensured that the access token has the required scope.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

With the correct access token and cookies, the script should successfully make a request to the time API endpoint and print the current time.

What could be causing the 401 Unauthorized error despite providing the correct access token? And are there any additional headers or parameters I might be missing?

>Solution :

To get correct result from the server you can use this example:

import re

import requests

url = "http://cyber.cs.du.edu/timekeeper/api/v1/time"

headers = {
    "X-TimeKeeper-Channel": "Web",
}

with requests.session() as s:
    html_text = s.get("http://cyber.cs.du.edu/timekeeper/").text

    token = re.search(r'__window_token = "([^"]+)', html_text).group(1)
    headers["Authorization"] = f"Bearer {token}"
    s.headers.update(headers)
    response = s.get(url).json()

    print(response)

Prints:

{'day': 9, 'hour': 21, 'microsecond': 754999, 'minute': 41, 'month': 11, 'second': 8, 'year': 2023}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading