cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
1564
Views
0
Helpful
5
Replies

How to reuse the vmanage rest API session?

The Viptela API documentation suggests to reuse the rest API session, but I am unable to reuse the session, and also the documentation does not have an example for that,

 

Below code give me an error if I store the cookies in a text file and reuse it for subsequent calls.

 

 

    def __init__(self):
        self.s = requests.Session()
        self.cookie_url = "https://" + base_url + "/j_security_check"
        self.login_data = {'j_username': username, 'j_password': password}
        try:
            self.res = self.s.post(self.cookie_url, verify=False,
                                   data=self.login_data,
                                   headers={
                                       "Accept": "application/json"
                                   })
            self.cookie = self.res.cookies.get_dict(VM_Constants.base_url)['JSESSIONID']

            with open("cookies.txt", "w") as f, open("token.txt", "w") as g:
                f.write(self.cookie)
        except Exception as e:
            logger.critical(f"Failed to get cookies e is {e}, login={self.login_data}", exc_info=True)
            raise SessionException("Unable to get cookies")

and when I execute the below function after storing the cookies, I get the error

 

 

 

    def get_omp_alarms(self):
        with open("cookies.txt", "r") as f:
            cookies = f.read()
        try:

            response = self.s.get("https://" + base_url + r"/dataservice/alarms",
                                  params={"query": json.dumps(query_active_alarms)}, verify=False,
                                  cookies={"Cookie:JSESSIONID": cookies})
            logger.info(f"Vmanage query successful {response.status_code}")
            print(response.text)
            pprint(response.status_code)
            pprint(response.json())
            return response.json()

        except Exception as e:
            logger.critical(f"Failed to get Alarms, e is {e}", exc_info=True)

 

 

I get back some random HTML page 

 

 

root - INFO - 11-Nov-21 20:29:50 - message: Vmanage query successful 200

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
    </head>
    <body onload="document.forms[0].submit()">
        <noscript>
            <p>
                <strong>Note:</strong> Since your browser does not support JavaScript,
                you must press the Continue button once to proceed.
            </p>
        </noscript>
        
        <form action="https&#x3a;&#x2f;&#x2f;cwa.xyz.com&#x2f;idp&#x2f;SSO.saml2" method="post">
            <div>
<input type="hidden" name="RelayState" value=""/>                
<input type="hidden" name="SAMLRequest" value="PD94bWwgdmVyc2lvbj0iMS4wIiBlb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zc0Vmk1SXFsa2N2OTlyT3ljMUsvbjhDZDJaaCtsMmt5U0YvNTBQZEVGYmpZTnpSSmQ0cUZheGNhUXE5V3J1MDdPL2x2CmowRDFEZCszbnNFckFnTUJBQUV3RFFZSktvWklodmNOQVFFTEJRQURnZ0VCQUQzMUsyOFV4amdyTXErS2hPSDM2b0F4aGdjUGp5OWsKOGpPNXZQSWRlN0ZyRGhIbjZhcys3M2xScStLNEV3YmtJYWR0YThkYWs2TXdGMzZzWDJqbkd6WG9PWDVya3ZBd2M3SFRobEJFejR3QgpDYllIV1h3ekQ3WGFqZ1Z4WnhXdjMwaVNHR0Q1UEtuTWVmVUhjc1R3dkdSQk1XSTc5UkNTaFBNdUZud2tsQVpScG5CYTFjRWpaTTlzCmhCV0RWcjlTL0NUS1hBVktJa2ppSXNSTEtGeUtBWnpIbmJWa1prTE9CR3ZFYW91b1M0U0NWanZacno4NFFPRW1MVlgvckFTRkhyR0YKOSsxVVZZVERsaWNQWktqQUJDUnBTYkFjNkttelQ2SzY3RHpKQ1liaXdvSzVmWFlpMkc0QkZWMldVYkw4YThXTHNPSGNDWmd1UXFETApNak1wNExrPTwvZHM6WDUwOUNlcnRpZmljYXRlPjwvZHM6WDUwOURhdGE+PC9kczpLZXlJbmZvPjwvZHM6U2lnbmF0dXJlPjwvc2FtbDJwOkF1dGhuUmVxdWVzdD4="/>                
                
            </div>
            <noscript>
                <div>
                    <input type="submit" value="Continue"/>
                </div>
            </noscript>
        </form>
    </body>
</html>
200
root - CRITICAL - 11-Nov-21 20:29:50 - message: Failed to get Alarms, e is Expecting value: line 2 column 1 (char 1)
Traceback (most recent call last):
  File "C:\Users\H376219\PycharmProjects\test.py", line 108, in alarms
    pprint(response.json())
  File "C:\Users\H376219\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 910, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\H376219\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\H376219\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\H376219\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)

 

 

 

 

 

5 Replies 5

@RakeshKulkarni82221 as far as I know the default session lifespan is 24 hours, and the session inactivity timeout is 30 minutes. You can also ask here https://community.cisco.com/t5/sd-wan-and-cloud-networking/bd-p/discussions-sd-wan 

 

Hope this helps.

Please mark this as helpful or solution accepted to help others
Connect with me https://bigevilbeard.github.io

Well then why it's failing when I reuse the same cookies for subsequent calls to vmanage endpoints.

It's not clear what you mean by lifespan of the session, when I request new cookies from the same ID I get new session which is also visible in the vmanage logs.

 

My question is simple how do I use the same session for multiple API calls, without obtaining new session everytime I make an API call.

@RakeshKulkarni82221 more details here on lifespan and API for SD-WAN auth - https://www.cisco.com/c/en/us/td/docs/routers/sdwan/configuration/sdwan-xe-gs-book/cisco-sd-wan-API-cross-site-request-forgery-prevention.html and  https://developer.cisco.com/docs/sdwan/#!authentication

 

With API session lifespan - the response for each API call includes the projected session timeout in the authentication element. The session timeout is calculated based on the session duration specified for the user (plus the current time). A timeout occurs if the session timeout is reached before any subsequent API calls are made. If a call occurs before the projected timeout, it is reset to the current time plus the session duration.

 

In your case, I am unsure why in your use cases repeated API endpoint calls you get a failure. This code example might help you https://developer.cisco.com/codeexchange/github/repo/bigevilbeard/Getting_Started_SDWAN or you can see examples in the https://developer.cisco.com/docs/sdwan/#!authentication this document shows the example for vManage post-19.2 - Session Cooke (jsessionid) and Token.

 

Hope this helps!

 

Please mark this as helpful or solution accepted to help others
Connect with me https://bigevilbeard.github.io

Your code does not save or re use the cookies or token.

Your code does not save or re use the cookies or token.