splunk-sdk-python icon indicating copy to clipboard operation
splunk-sdk-python copied to clipboard

splunklib.binding.AuthenticationError: Autologin succeeded, but there was an auth error on next request. Something is very wrong.

Open anumpatel opened this issue 8 years ago • 22 comments

  • Version of the project : splunk-sdk==1.6.5
  • Platform version : Ubuntu 16.04.3 LTS x86_64
  • Framework version : Python 3.5.2
  • Splunk version : Splunk Enterprise 7.1.1

Code that produces the exception :

import splunklib.client as client
import splunklib.results as results
service = client.connect(host='xx', username='xx', password='xx', autologin=True)

search_oneshot = 'search index=xx sourcetype=xx .......'
kwargs_export = {"earliest_time": "-4Hr",
                 "latest_time": "now",
                 "search_mode": "normal"}

oneshot_results = service.jobs.oneshot(search_oneshot, **kwargs_export)
reader = results.ResultsReader(oneshot_results)
for item in reader:
        print(item)

This simple script executes sometimes without any issue. But when not, it produces :

Traceback (most recent call last):
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 289, in wrapper
    return request_fun(self, *args, **kwargs)
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 71, in new_f
    val = f(*args, **kwargs)
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 742, in post
    response = self.http.post(path, all_headers, **query)
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 1208, in post
    return self.request(url, message)
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 1228, in request
    raise HTTPError(response)
splunklib.binding.HTTPError: HTTP 401 Unauthorized -- call not properly authenticated

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 231, in _handle_auth_error
    yield
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 300, in wrapper
    return request_fun(self, *args, **kwargs)
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 71, in new_f
    val = f(*args, **kwargs)
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 742, in post
    response = self.http.post(path, all_headers, **query)
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 1208, in post
    return self.request(url, message)
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 1228, in request
    raise HTTPError(response)
splunklib.binding.HTTPError: HTTP 401 Unauthorized -- call not properly authenticated

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "splunk_ex.py", line 10, in <module>
    oneshot_results = service.jobs.oneshot(search_oneshot, **kwargs_export)
  File "path_to_env/lib/python3.5/site-packages/splunklib/client.py", line 3041, in oneshot
    **params).body
  File "path_to_env/lib/python3.5/site-packages/splunklib/client.py", line 808, in post
    return self.service.post(path, owner=owner, app=app, sharing=sharing, **query)
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 300, in wrapper
    return request_fun(self, *args, **kwargs)
  File "/usr/lib/python3.5/contextlib.py", line 77, in __exit__
    self.gen.throw(type, value, traceback)
  File "path_to_env/lib/python3.5/site-packages/splunklib/binding.py", line 234, in _handle_auth_error
    raise AuthenticationError(msg, he)
splunklib.binding.AuthenticationError: Autologin succeeded, but there was an auth error on next request. Something is very wrong.

I am not able to predict when it fails and when not. Its pretty random. Am I hitting the resource limit or is it something else?

anumpatel avatar Aug 29 '18 22:08 anumpatel

Is Python 3 supported now? I thought it was just Python 2.x?

swedishmike avatar Aug 30 '18 11:08 swedishmike

@swedishmike Well, on README, it says : The Splunk SDK for Python requires Python 2.7+.

anumpatel avatar Aug 31 '18 16:08 anumpatel

@anumpatel Thanks for the detailed bug report! It's certainly possible to hit a limit like maximum concurrent connections. I would take a look through $SPLUNK_HOME/var/log/splunk/splunkd.log for any errors.

@swedishmike Yes, Python 3 has been supported since #191 which landed in v1.6.3.

shakeelmohamed avatar Aug 31 '18 23:08 shakeelmohamed

I just ran into this issue myself... a little sad that there hasn't been any comment here in a year and a half. I'm still debugging it, but is there a chance that your Splunk instance is load balanced?

I hit this identical issue with the Ruby SDK, and it turned out that my company's Splunk Cloud instance (i.e. https://mycompany.splunkcloud.com:8089) is a load balanced cluster, but the Splunk Ruby SDK was ignoring the session stickyness cookies it returns... so auth would work on any requests that happened to be load balanced to the same cluster node as the initial login, or fail on all others. The Ruby SDK has a basic option on the connection to force it to send basic auth with every request to avoid this, but the Python SDK doesn't seem to have that option.

jantman avatar Apr 09 '20 11:04 jantman

Just an update if anyone else runs into this and has the same problem that I did... while it's not documented, the connect() method, and the underlying Service() and Context() class constructors, do take a basic=True keyword argument. This fixed it for me. It seems like, just like the Ruby SDK, this completely ignores cookies set by Splunk which breaks the load balancing.

jantman avatar Apr 09 '20 11:04 jantman

I've just now run into this issue and the basic=True trick does not work for me. There are several calls to the Splunk service in my Python script, and it is random which call it fails on.

Frechetta avatar May 07 '20 21:05 Frechetta

client.connect(..., basic=True) work for me, or you can try to keep your requests in one session.

zgy730 avatar Oct 09 '20 03:10 zgy730

Hi everyone, I am testing a custom command and ran into the same problem. In my case, I am starting a connection using the the session key: client.connect(token=self._metadata.searchinfo.session_key, autologin=True)

I tried to add basic=True to the call but that doesn't work for me.

Is there any solution for this problem?

viniciusfacco avatar Nov 24 '20 21:11 viniciusfacco

@viniciusfacco, If you have user and password, you can try to use Basic token instead of getting session key.

zgy730 avatar Nov 25 '20 11:11 zgy730

@x-devplus, In my setup I do not have the user and password.

However, I found an alternative that worked for me. The custom command already receives a service object that is logged in. So, instead of creating a new service with client.connect(), I just use the available one calling self.service. In my case, I can run searches this way:

oneshot_results = self.service.jobs.oneshot(search_oneshot, **kwargs_export)

viniciusfacco avatar Nov 25 '20 19:11 viniciusfacco

Hi, anyone has a solution for this one? I'm facing the same challenge and the following is the error message:

Autologin succeeded, but there was an auth error on next request. Something is very wrong.
Traceback (most recent call last):
  File "/home/airflow/.local/lib/python3.6/site-packages/splunklib/binding.py", line 290, in wrapper
    return request_fun(self, *args, **kwargs)
  File "/home/airflow/.local/lib/python3.6/site-packages/splunklib/binding.py", line 71, in new_f
    val = f(*args, **kwargs)
  File "/home/airflow/.local/lib/python3.6/site-packages/splunklib/binding.py", line 686, in get
    response = self.http.get(path, all_headers, **query)
  File "/home/airflow/.local/lib/python3.6/site-packages/splunklib/binding.py", line 1194, in get
    return self.request(url, { 'method': "GET", 'headers': headers })
  File "/home/airflow/.local/lib/python3.6/site-packages/splunklib/binding.py", line 1255, in request
    raise HTTPError(response)
splunklib.binding.HTTPError: HTTP 401 Unauthorized -- call not properly authenticated

I'm calling the Splunk queries on an hourly basis, and running a few splunk queries at the same time. Some of the searches work, while some don't. There isn't any consistent patterns about which works and which doesn't. So, I'm curious whether there is any "limit" on how many searches can run at the same time in one server.

I'm using normal search approach, exec_mode = "normal".

For the connection, client.connect and included autologin=True. So, the error commented that Autologin succeeded, but there was an auth error on next request. Something is very wrong.. I'm wondering what does it mean by auth error on next request? And, what is very wrong?

Environment: splunk-sdk==1.6.14 Splunk Cloud==8.0.2006

aluxh avatar May 19 '21 04:05 aluxh

Hi all, SDK supports connection to the Splunk using following different ways using client.connect :-

  1. user credentials (username and password)
  2. using the User's session key
  3. using the bearer token

Here we have an autologin=true flag, which used in combination with the username/password allows the connection to be re-established once the session expires i.e it creates a new session key to be used for the next API calls.

The error code behind the mentioned error message is 401 which indicates authorisation failure due to the expired session key/token used for the connection

@aluxh the default session expiration is set to 1hour, as you mentioned some queries are executing on hourly basis its highly possible for the session key to expire and raise the error. We would request you to confirm if you are using the username/password combination with autologin=true so that the session can be re-established and avoid any authentication errors.

We would recommend to update to the latest version of splunk sdk, and let us know if the issue still persists. Closing the issue for now. Thanks

ashah-splunk avatar Aug 31 '21 13:08 ashah-splunk

Is this issue resolved as I am still getting this error with version splunk-sdk==1.6.18 ? As suggested on this thread, I have tried adding basic=True but that seems to be slowing down the splunk queries. Is this slowness due to the fact that for all the queries it is doing authentication using username/password (as we are using basic=True).

service = client.connect(host=host_name,
                             scheme="https",
                             port=splunk_conf["port"],
                             username,
                             password,
                             autologin=True,
                             verify=False)

I tried with latest version splunk-sdk==1.7.2 also and started getting the below error

Exception while performing Splunk search. retry Count: 0... Authentication Failed! If session token is used, it seems to have been expire

Wanted to know if there is any other fix for this issue ? Thanks in advance!

RahulGuleria avatar Sep 19 '22 18:09 RahulGuleria

Even I am facing this issue

AbhijayJ avatar Sep 20 '22 07:09 AbhijayJ

@RahulGuleria , @AbhijayJ I was able to reproduce the issue when I used wrong username and/or password along with basic=True, so I would request you to verify the username/password and try again. Please let us know if it resolves the issue.

ashah-splunk avatar Sep 20 '22 09:09 ashah-splunk

@ashah-splunk - The issue is not with the username/password. We are executing multiple splunk queries and we are not getting this error all the time, in fact most of the time queries execute correctly. We are getting this error intermittently. If we try without the flag basic=True only then we are getting this error.

If we try with flag basic=True, we do not get this error but it slows down our splunk queries considerably.

I wanted to know if there is any fix for this issue (other than basic=True) ?

RahulGuleria avatar Sep 20 '22 09:09 RahulGuleria

@RahulGuleria thank you for the details of the issue, we will look into this. In the meanwhile I would like to recommend using bearer token, as it has the flexibility that allows to set the expiration duration as per the requirement. As username/password are not required while using Bearer token, it would improve the performance as well.

ashah-splunk avatar Sep 20 '22 09:09 ashah-splunk

@ashah-splunk Thanks for your quick response. We tried that approach too, as we are using multiple-hosts to connect to, so we would require multiple bearer token - separate token for each host. Token management will become a problem in that case as it is difficult to manage different bearer tokens and their expiry.

Is there any way, we can generate bearer token using api or we can set/extend its life using api. Currently we contact splunk-support team in our company to generate and provide bearer token.

RahulGuleria avatar Sep 20 '22 10:09 RahulGuleria

@RahulGuleria Creating auth tokens and managing expiry is currently not in scope of this SDK. Please take a look at these docs on the Authentication REST API. Also, here is some docs on creating and managing expiry of authentication tokens. Hope this is helpful.

ncanumalla-splunk avatar Sep 23 '22 19:09 ncanumalla-splunk

Hi @ncanumalla-splunk @ashah-splunk, we face the same problem intermittently when using basic=true. I see this issue was closed even tho no solution was given, only the token workaround (which is also problematic in our case). Is the official statement from Splunk that username/password method is not supported when using the SDK?

ShahafBenYakir avatar Jul 29 '24 10:07 ShahafBenYakir