Once again I venture into the lands of poorly documented keystoneauth1 calls. This time, I want to be able to validate if a stored keystone authentication token is valid. Here’s the best I could come up with, I’d be interested in others have something better. For this to work, we need a service account to create a keystone client with, and then we can ask that client questions about random other tokens…
from keystoneauth1 import exceptions
from keystoneauth1.identity import v3
from keystoneauth1 import session
from keystoneclient.v3 import client
def validate_keystone_token(service_auth, token):
"""Validate a keystone token.
Returns True if the token is valid, False otherwise.
"""
# We need a keystone client as the service
service_session = session.Session(auth=service_auth)
service_keystone = client.Client(session=service_session)
try:
user = service_keystone.tokens.validate(token)
except exceptions.http.NotFound:
return False
# Require that there be an access group with our configured name
group = None
for g in service_keystone.groups.list():
if g.name == 'mygroup':
group = g
if not group:
return False
# Require that the user be in that group
try:
service_keystone.users.check_in_group(user.user_id, group.id)
except exceptions.http.NotFound:
return False
return True
# Authenticate the service user
service_auth = v3.Password(
auth_url='http://kolla.home.stillhq.com:5000',
username='admin',
password='...',
project_name='admin',
user_domain_id='default',
project_domain_id='default')
# Create a token we can test
user_auth = v3.Password(
auth_url='http://kolla.home.stillhq.com:5000',
username='mikal',
password='...',
project_name='admin',
user_domain_id='default',
project_domain_id='default')
sess = session.Session(auth=user_auth)
token = sess.get_token()
# The token should be valid
assert(validate_keystone_token(service_auth, token))
# Make that token invalid
token += 'foo'
assert(not validate_keystone_token(service_auth, token))
# A user not in the group
user_auth = v3.Password(
auth_url='http://kolla.home.stillhq.com:5000',
username='nomikal',
password='...',
project_name='admin',
user_domain_id='default',
project_domain_id='default')
sess = session.Session(auth=user_auth)
token = sess.get_token()
assert(not validate_keystone_token(service_auth, token))
I’ve updated this with a slightly better version based on more Googling and arguing with friends on the internet.