How to authenticate using Authentication API

Hi , I am following the link Authentication document. I have provided 'http://localhost/' as my redirect uri.

url = f'https://api-v2.upstox.com/login/authorization/dialog?response_type=code&client_id={client_id}&redirect_uri={redirect_uri}&state={state}'

# Open the URL in the default web browser
webbrowser.open(url)

I am able to get a code in the format
http://localhost/?code=xxxx&state=Your-Optional-State-Parameter-Here

Then , I am giving input in the following script


import requests

# Replace these with your actual details
auth_code = 'auth_code_from_prev_step'
client_id = 'api_key'
client_secret = 'client_secret'
redirect_uri = 'http://localhost/'

url = 'https://api-v2.upstox.com/login/authorization/token'
headers = {
    'accept': 'application/json',
    'Api-Version': '2.0',
    'Content-Type': 'application/x-www-form-urlencoded'
}
data = {
    'code': auth_code,
    'client_id': client_id,
    'client_secret': client_secret,
    'redirect_uri': redirect_uri,
    'grant_type': 'authorization_code'
}

response = requests.post(url, headers=headers, data=data)

if response.status_code == 200:
    print('Success:', response.json())
else:
    print('Failed:', response.status_code, response.text)

However , this runs for the first time, but next time onwards
I am getting

Failed: 401 {"status":"error","errors":[{"errorCode":"UDAPI100057","message":"Invalid Auth code","propertyPath":null,"invalidValue":null,"error_code":"UDAPI100057","property_path":null,"invalid_value":null}]}

How long is the authentication code valid ?

@coolcoder code sent as part of this request is valid for a single use, regardless of whether the access token generation succeeds or encounters an issue.

This information is also stated in the note section of the API documentation at Upstox, which can be found here:

Hi @Pradeep_Jaiswar , thanks for prompt response. Is there any way I can use the APIs using single authentication mechanism ?

I hope my previous response was helpful.

Could you please clarify what you mean by ā€œsingle authentication mechanismā€ here?

Hi @Pradeep_Jaiswar , thanks for prompt response. I mean to say I would like to login using the API and fetch data through websocket and get index Option / Futures data (like OI , volume). Do I need to make separate call everytime ?

Hi @Pradeep_Jaiswar , good morning. Please let me know if my query/ requirements were not clear.

You can readily achieve what youā€™re aiming for. A great starting point is to familiarize yourself with the documentation.

To begin with the login process, please consult the login section of the documentation at Login | Upstox Developer API. Once you successfully do login, you will receive an access token, valid for one day, which allows you to access other APIs, including the websocket connection.

For comprehensive information and guidelines on websocket implementation, please refer to the websocket section in the documentation at Websocket | Upstox Developer API which comes with an example.

I hope this guidance will be helpful to you.

Hi @Pradeep_Jaiswar , thanks for your guidance.

I generated the token throughToken API .
and then replaced the token value in this websocket code (before running the code , I have correctly setup protoc and compiled the proto file to generate python file, there is no issue in that).

After running the code ,
I am getting following error

 File "/usr/local/anaconda3/envs/python3_8/lib/python3.8/site-packages/upstox_client/rest.py", line 228, in GET
    return self.request("GET", url,
  File "/usr/local/anaconda3/envs/python3_8/lib/python3.8/site-packages/upstox_client/rest.py", line 222, in request
    raise ApiException(http_resp=r)
upstox_client.rest.ApiException: (401)
Reason: Unauthorized
HTTP response body: b'{"status":"error","errors":[{"errorCode":"UDAPI100050","message":"Invalid token used to access API","propertyPath":null,"invalidValue":null,"error_code":"UDAPI100050","property_path":null,"invalid_value":null}]}'

But when I am using the same token in url = 'https://api-v2.upstox.com/login/authorization/token' it is working fine. (Ofcourse , after single use the token is getting expired , and I am regenerating the token again ). But , using Websocket , I am getting Unauthorized

What am I missing here ? Please help

@coolcoder

It seems like youā€™re using the same authorization code for both the token API and the websocket API, which works for the token API but not for the websocket API. This is because the authorization code is intended for single use, specifically to generate an access_token via the /token API. For all subsequent API calls, you should use the access_token obtained from the /token API.

To resolve this, youā€™ll need to generate a new code during the OAuth process, use it to obtain an access_token from the /token API, and then use this access_token for all your other API calls.

Weā€™re providing detailed error messages to assist with troubleshooting. The message ā€œInvalid token used to access APIā€ indicates an issue with the access_token in the header. I recommend closely reading these error messages and referring to our Documentation (API Documentation ā€“ Fast Secure Free ā€“ Upstox | Upstox Developer API) for further guidance. Understanding these resources together will help you effectively address the problem.

Let me know if this solution works for you.

Thanks!

1 Like

Thanks a lot for your support and prompt response . It is resolved.

1 Like

Hi @Pradeep_Jaiswar , Iā€™m using automation to retrieve the code followed by generating the access token using Playwright. However, Iā€™m encountering difficulty passing the Cloudflare human/robot check. Is there a way to bypass it or resolve this issue?

2 Likes

Same issue hereā€¦


stuck at that.,

1 Like

Hi @Pradeep_Jaiswar

Please think of people who uses Linux headless chrome for login.

Your internal design team has lots of skill gaps to understand current web architecture.

Please help with an workaround or implement better design

2 Likes

Is anyone able to successfully implement headless oauth? How can we get the code without going through the web-browser session?

Thanks,
Chaitanya