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!

Threat Hunting Unlocked: How to Uplevel Your Threat Hunting With the PEAK Framework ...

WATCH NOWAs AI starts tackling low level alerts, it's more critical than ever to uplevel your threat hunting ...

Splunk APM: New Product Features + Community Office Hours Recap!

Howdy Splunk Community! Over the past few months, we’ve had a lot going on in the world of Splunk Application ...

Index This | Forward, I’m heavy; backward, I’m not. What am I?

April 2024 Edition Hayyy Splunk Education Enthusiasts and the Eternally Curious!  We’re back with another ...