Skip to content

Basic authentication #430

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
aabed opened this issue Jan 14, 2018 · 16 comments
Closed

Basic authentication #430

aabed opened this issue Jan 14, 2018 · 16 comments
Labels
lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed.

Comments

@aabed
Copy link

aabed commented Jan 14, 2018

I am trying to access my cluster using basic authentication
but I am afraid that the docs is not clear regarding this

so I was wondering how to achieve that

@wanghonglei5181
Copy link

me too

@wanghonglei5181
Copy link

i don't kown how to set params
python console:
console>>> from kubernetes import client,config
console>>>help(config.load_kube_config)
load_kube_config(config_file=None, context=None, client_configuration=None, persist_config=True)
Loads authentication and cluster information from kube-config file
and stores them in kubernetes.client.configuration.

:param config_file: Name of the kube-config file.
:param context: set the active context. If is set to None, current_context
    from config file will be used.
:param client_configuration: The kubernetes.client.Configuration to
    set configs to.
:param persist_config: If True, config file will be updated when changed
    (e.g GCP token refresh).

@wanghonglei5181
Copy link

/usr/local/lib/python2.7/dist-packages/kubernetes/client/configuration.py
i found this file

@tomplus
Copy link
Member

tomplus commented Jan 16, 2018

Try to launch one of the examples, for instance examples/example1.py. It should work out of the box if your kubectl works. It tries to find a configuration file using the environment variable named KUBECONFIG or path ~/.kube/config. You can use load_kube_config(config_file='/your/path/to/config/file') in more complicated scenarios.

Enjoy :)

@wanghonglei5181
Copy link

wanghonglei5181 commented Jan 17, 2018

@tomplus
kubernetes is a part of my project,
In my computer,there is nothing about kube.
i need connect remote kube api, can i pass some params to load_kube_config ,
for example: load_kube_config(username="username",password="password",url="url")
i dont want to write a config file.

@wanghonglei5181
Copy link

wanghonglei5181 commented Jan 17, 2018

shell cmd:kubectl config set-cluster default --server=https://IP:6443 --certificate-authority=/root/.kube/ca.pem
shell cmd:kubectl config set-credentials admin --certificate-authority=/root/.kube/ca.pem --client-key=/root/.kube/admin-key.pem --client-certificate=/root/.kube/admin.pem
shell cmd:kubectl config set-context default --cluster=default --user=admin
shell cmd:kubectl config use-context default

worked!!

root@honglei-virtual-machine:~/.kube# cat /root/.kube/config
apiVersion: v1
clusters:

  • cluster:
    certificate-authority: ca.pem
    server: https://IP:6443
    name: default
    contexts:
  • context:
    cluster: default
    user: admin
    name: default
    current-context: default
    kind: Config
    preferences: {}
    users:
  • name: admin
    user:
    as-user-extra: {}
    client-certificate: admin.pem
    client-key: admin-key.pem

@aabed
Copy link
Author

aabed commented Jan 22, 2018

All the solutions are towards using the config file
I don't want to use the config file

@charly37
Copy link
Contributor

charly37 commented Jan 22, 2018

Same here. I m trying to target a kube cluster deployed on Google cloud (Google Kube Engine).
This is working from any server and do not rely on any config file

from kubernetes import client, config

#see https://kubernetes.io/docs/tasks/administer-cluster/access-cluster-api/#accessing-the-cluster-api to know how to get the token
#The command look like kubectl get secrets | grep default | cut -f1 -d ' ') | grep -E '^token' | cut -f2 -d':' | tr -d '\t' but better check the official doc link 
aToken="eyJhXXXXXXXX82IKq0rod1dA"


# Configs can be set in Configuration class directly or using helper utility
configuration = client.Configuration()
configuration.host="https://XXX.XXX.XXX.XXX:443"
configuration.verify_ssl=False
configuration.debug = True

#Maybe there is a way to use these options instead of token since they are provided in Google cloud UI
#configuration.username = "admin"
#configuration.password = "XXXXXXXXXXX"
configuration.api_key={"authorization":"Bearer "+ aToken}
client.Configuration.set_default(configuration)

v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
	print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

I will do a PR to see if we could add it in the example section to demonstrate the use of the "configuration" object and the way to configure the library to target a remote Kube cluster.

@charly37
Copy link
Contributor

charly37 commented Jan 23, 2018

OK so after more digging...
I do not thing the BASIC auth is usable for several reasons.

First the documentation https://github.com/kubernetes-client/python/blob/master/kubernetes/README.md (at the very end of page) only mention the "BearerToken" method (which is the one I describe in my previous answer). There is nothing about the basic auth (even if it is supported bu Kube as explain on their official doc : https://kubernetes.io/docs/admin/authentication/ "Kubernetes uses client certificates, bearer tokens, an authenticating proxy, or HTTP basic auth to authenticate....")

Second I check in the code and the method "get_basic_auth_token" in configuration.py is never call anywhere (and it is the only one dealing with username/password field).

Then I try to "hack" a little the python code by modifying the class configuration and change its auth_setting with that

    def auth_settings(self):
        """
        Gets Auth Settings dict for api client.

        :return: The Auth Settings information dict.
        """
        return {
            'BearerToken':
                {
                    'type': 'api_key',
                    'in': 'header',
                    'key': 'authorization',
                    'value': self.get_api_key_with_prefix('authorization')
                },
                'http_basic_test':
                {
                    'type': 'basic',
                    'in': 'header',
                    'key': 'Authorization',
                    'value': self.get_basic_auth_token()
                },
        }

I just added the "http_basic_test" here. Then you can take any functional class like ""core_v1_api and modify the method you plan to use (list_pod_for_all_namespaces_with_http_info in my case) and modify the auth part of the code. Replace
auth_settings = ['BearerToken']
with
auth_settings = ['http_basic_test']
and then you can use username/password to authenticate (I verified and it works)

You should have valid response and even see the basic auth info if you activate debug log (like it is done in my previous answer):
send: b'GET /version/ HTTP/1.1\r\nHost: XXX.XXX.XXX.XXX\r\nAccept-Encoding: identity\r\nAccept: application/json\r\nContent-Type: application/json\r\nUser-Agent: Swagger-Codegen/4.0.0/python\r\nAuthorization: Basic YWRXXXXXXXXXXXRA==\r\n\r\n'
To sum up...... You can not use the "HTTP basic auth" but "bearer tokens" works fine. There is probably an option in the swagger generator to activate the basic auth. I will dig more latter ;)

I hope it already help a little (my advise : go with my previous answer and bearer tokens for now)
BTW if anybody could tell me how the API is generated it could help me find the option to have basic auth.

@sarudak
Copy link

sarudak commented Jan 24, 2018

We have been trying to use basic auth also. Basically we want to use any auth method that allows us to get credentials from the GKE api and use that to hit the kubernetes API. We can't rely on the kube config file because we may be operating against many different clusters even ones we just created and don't want to shell out to the gcloud API.

@charly37
Copy link
Contributor

charly37 commented Feb 4, 2018

I made some more digging yesterday and confirms my previous idea that the BASIC auth is not supported by this library (and probably by other libs generated from the kube swagger file).

The lib is generated from this swagger file:
https://raw.githubusercontent.com/kubernetes/kubernetes/master/api/openapi-spec/swagger.json
that do not contains the basic auth method in the security definitions so the generated python code do not contains the code to allow it.

I forked Kube and modify the swagger file to allow it kubernetes/kubernetes@master...charly37:master and generate again the python lib (see https://github.com/kubernetes-client/gen) and then installed this new version on my server and was finally able to use the BASIC auth to communicate with my GKE cluster.

I will try to find why the basic auth is not part of the Kube swagger def.

If you want more detail about the investigation/test I put that on my blog http://djynet.net/?p=918

Will update this ticket once i have more info.

@fejta-bot
Copy link

Issues go stale after 90d of inactivity.
Mark the issue as fresh with /remove-lifecycle stale.
Stale issues rot after an additional 30d of inactivity and eventually close.

If this issue is safe to close now please do so with /close.

Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/lifecycle stale

@k8s-ci-robot k8s-ci-robot added the lifecycle/stale Denotes an issue or PR has remained open with no activity and has become stale. label Apr 22, 2019
@fejta-bot
Copy link

Stale issues rot after 30d of inactivity.
Mark the issue as fresh with /remove-lifecycle rotten.
Rotten issues close after an additional 30d of inactivity.

If this issue is safe to close now please do so with /close.

Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/lifecycle rotten

@k8s-ci-robot k8s-ci-robot added lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed. and removed lifecycle/stale Denotes an issue or PR has remained open with no activity and has become stale. labels May 22, 2019
@fejta-bot
Copy link

Rotten issues close after 30d of inactivity.
Reopen the issue with /reopen.
Mark the issue as fresh with /remove-lifecycle rotten.

Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/close

@k8s-ci-robot
Copy link
Contributor

@fejta-bot: Closing this issue.

In response to this:

Rotten issues close after 30d of inactivity.
Reopen the issue with /reopen.
Mark the issue as fresh with /remove-lifecycle rotten.

Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/close

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

@ghostcodersmn
Copy link

I found a way how to use Basic Authentication.
`configuration = kubernetes.client.Configuration()
configuration.host = "https://ip:6443"
configuration.verify_ssl = True
configuration.username = "user"
configuration.password = "pass"
basic_auth_token = configuration.get_basic_auth_token()
configuration.ssl_ca_cert="./ssl_ca_cert.crt"

api_client = kubernetes.client.ApiClient(configuration, header_name="authorization", header_value=basic_auth_token)
core_v1_api = kubernetes.client.CoreV1Api(api_client)
try:
namespaces = core_v1_api.list_namespace()
print(namespaces)
except Exception as e:
print(e)`

You can give a header_name and a header_value to the constructor of the ApiClient. The configuration class has a method get_basic_auth_token to get the Basic Auth String. So you can use this to create an authorization header with the basic auth string as a value 👍

i hope this helps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed.
Projects
None yet
Development

No branches or pull requests

8 participants