All Apps and Add-ons

Splunk 6 Web Framework - Python SDK - How to get logged in username?

joshuamcqueen
Path Finder

Hey Splunk Gurus,

I'm writing a custom Splunk 6 web framework application and I'm trying to get the username server-side.

I know this sounds very (very!) simple, but I can't seem to get it. The username keeps coming up blank.

Starting with a completely new app, I enter the following:

@render_to('my_app:home.html')
@login_required
def home(request):

    service = request.service
    logger.debug(service.username)

    return {
        "message": service.username,
    }

I couldn't get that to work, so I said "screw it -- I'll just use REST". That got me close but no cigar:

josh_rest = service.get('/services/authentication/current-context')
logger.debug(josh_rest.body)  #this displays the XML 

I did end up getting the XML for the REST endpoint (which does indeed contain the logged in username!) but I can't figure out how to use splunklib.data.load() to parse it effectively.

I even saw this in the documentation (but it doesn't work for me)

Anyhow, if you have any insight into how to get the username, please let me know. Thanks!!

0 Karma
1 Solution

ineeman
Splunk Employee
Splunk Employee

You should be able to do:


request.user.username

That should give you the username of the currently logged in user.

View solution in original post

ineeman
Splunk Employee
Splunk Employee

You should be able to do:


request.user.username

That should give you the username of the currently logged in user.

ineeman
Splunk Employee
Splunk Employee

Note that request.user.realname may be different, if the user has a real name in. For example, my username might be ineeman, but my realname might be Itay Neeman.

0 Karma

joshuamcqueen
Path Finder

Both of these work: Thanks for the help!

request.user.realname
request.user.name

0 Karma

joshuamcqueen
Path Finder

I came up with a solution, though it's not very pythonic. Basically I take the XML of the REST response and grab the specific strings. It works but it's kinda ugly.

import re

response = service.get('/services/authentication/current-context')

result = re.search('<s:key name="username">(.*)</s:key>', response.body)
username = result.group(1)

result = re.search('<s:key name="realname">(.*)</s:key>', response.body)
realname = result.group(1)

print username
print realname
Get Updates on the Splunk Community!

Earn a $35 Gift Card for Answering our Splunk Admins & App Developer Survey

Survey for Splunk Admins and App Developers is open now! | Earn a $35 gift card!      Hello there,  Splunk ...

Continuing Innovation & New Integrations Unlock Full Stack Observability For Your ...

You’ve probably heard the latest about AppDynamics joining the Splunk Observability portfolio, deepening our ...

Monitoring Amazon Elastic Kubernetes Service (EKS)

As we’ve seen, integrating Kubernetes environments with Splunk Observability Cloud is a quick and easy way to ...