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!

.conf24 | Registration Open!

Hello, hello! I come bearing good news: Registration for .conf24 is now open!   conf is Splunk’s rad annual ...

ICYMI - Check out the latest releases of Splunk Edge Processor

Splunk is pleased to announce the latest enhancements to Splunk Edge Processor.  HEC Receiver authorization ...

Introducing the 2024 SplunkTrust!

Hello, Splunk Community! We are beyond thrilled to announce our newest group of SplunkTrust members!  The ...