Crouch
Crouch

Reputation: 1

Good way/place to authenticate Keystone/Openstack API from Django

This is my first post on Stackoverflow and I'm new to Django, I hope you'll understand.

I want to use Django to provide a portal with authentication, which will have to consume an Keystone/Openstack API, to create/delete Projects, grant/remove rights.

Openstack provides a RestFul API, on which I have to authenticate (I provide credentials, and receive back a token). I have 2 possibilities to access this API:

  1. Using python client: python-keystoneclient
  2. Using directly the restfulAPI

Nevermind the option 1 or 2, I'm able to login and interact with the API, I do this in the view.

My problem is, each time I change the page/view, I have to authenticate again. I don't know how to use/share the "session or client object" in other views.

>>> from keystoneauth1.identity import v3
>>> from keystoneauth1 import session
>>> from keystoneclient.v3 import client
>>> auth = v3.Password(auth_url='https://my.keystone.com:5000/v3',
...                    user_id='myuserid',
...                    password='mypassword',
...                    project_id='myprojectid')
>>> sess = session.Session(auth=auth)
>>> keystone = client.Client(session=sess, include_metadata=True)

I tried to pass the object as a session variable with request.session and request.session.get, but the object is not serializable. I serialized it, but I can't use it on the other view.

Maybe I shouldn't access the API in the view? I'm sure I'm not the first in this usecase, regardless of the remote API. But I googled a lot without finding a proper way. Maybe I don't search with the right words

Thanks for your help.

Upvotes: 0

Views: 251

Answers (1)

Crouch
Crouch

Reputation: 1

I did it like this and it works well:

in apps.py:

from django.apps import AppConfig
from keystoneauth1.identity import v3
from keystoneauth1 import session
from keystoneclient.v3 import client

class MyAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'mySharedVar'
    auth = v3.Password(auth_url='https://my.keystone.com:5000/v3', user_id='myuserid', password='mypassword',project_id='myprojectid')
    ses1 = session.Session(auth=auth)

in my views, I can now access the "share variable" with:

from keystoneauth1.identity import v3
from keystoneauth1 import session
from keystoneclient.v3 import client

@login_required
def list_project(request):
    sharedVar=apps.get_app_config('mySharedVar')
    keystone = client.Client(session=sharedVar.ses1, include_metadata=True)
    pl = keystone.projects.list()
    context = {
        "title": "Project List",
        "projects": pl.data
    }
    return render(request, "myapp/list_project.html",context=context)

I hope this can help someone.

Upvotes: 0

Related Questions