<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: How to get HTTP header value in custom python web service? in Splunk Dev</title>
    <link>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281249#M3536</link>
    <description>&lt;P&gt;Yeah that's what I meant.  But then you've got to hard code a user/pass etc.&lt;/P&gt;

&lt;P&gt;Using a Splunk search command however, you can pass the auth token with the correct commands.conf settings.  I don't know if that's an option for you or not.  You know... Somehow I do this with my rest endpoints because I trigger a restart message after the user clicks save on setup.xml.  Let me get back to you...&lt;/P&gt;</description>
    <pubDate>Thu, 15 Dec 2016 12:19:04 GMT</pubDate>
    <dc:creator>jkat54</dc:creator>
    <dc:date>2016-12-15T12:19:04Z</dc:date>
    <item>
      <title>How to get HTTP header value in custom python web service?</title>
      <link>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281246#M3533</link>
      <description>&lt;P&gt;Hi,&lt;/P&gt;

&lt;P&gt;This is another question about custom python controllers and endpoints.&lt;/P&gt;

&lt;UL&gt;
&lt;LI&gt;I have programmed a custom endpoint available at: &lt;CODE&gt;&lt;A href="http://localhost:8080/en-US/custom/my_app/my_script/test" target="test_blank"&gt;http://localhost:8080/en-US/custom/my_app/my_script/test&lt;/A&gt;&lt;/CODE&gt;&lt;/LI&gt;
&lt;LI&gt;I make an &lt;STRONG&gt;ajax request&lt;/STRONG&gt; from a browser &lt;STRONG&gt;inserting an  &lt;CODE&gt;Authorization&lt;/CODE&gt; header&lt;/STRONG&gt;.&lt;/LI&gt;
&lt;LI&gt;I am trying to read the value of this header in my python controller, but it doesn't appear.&lt;/LI&gt;
&lt;LI&gt;I have tried using &lt;STRONG&gt;cherrypy headers&lt;/STRONG&gt;, but although I get plenty of HTTP headers, &lt;STRONG&gt;I can't see the one I want&lt;/STRONG&gt;: &lt;CODE&gt;Authorization&lt;/CODE&gt;.&lt;/LI&gt;
&lt;/UL&gt;

&lt;P&gt;&lt;STRONG&gt;Any hints on why I get some headers but not that one?&lt;/STRONG&gt;&lt;/P&gt;

&lt;P&gt;I have my endpoint script in appserver/controllers:&lt;/P&gt;

&lt;PRE&gt;&lt;CODE&gt; #my_script.py
 import splunk.appserver.mrsparkle.controllers as controllers
 from splunk.appserver.mrsparkle.lib.decorators import expose_page
 import cherrypy

 class Controller(controllers.BaseController):
     @expose_page(must_login=False, methods=['GET']) 
     def test(self, **kwargs) :
         return cherrypy.request.headers.output()
&lt;/CODE&gt;&lt;/PRE&gt;

&lt;P&gt;This is my ajax request:&lt;/P&gt;

&lt;PRE&gt;&lt;CODE&gt;$.ajax({
    type: "GET",
    crossDomain:true,
    url: "http://localhost:8080/en-US/custom/my_app/my_script/test",
    headers: {
        "Authorization" : "whatever"
    },
    success: function (response){
        console.log(response);
    }
});
&lt;/CODE&gt;&lt;/PRE&gt;

&lt;P&gt;This is what I get as a response:&lt;/P&gt;

&lt;PRE&gt;&lt;CODE&gt;[('Te', 'chunked'),  
('Accept-Encoding', 'gzip'),
('Host', 'localhost:8080'), 
('Accept', '*/*'), 
('X-Splunkd', 'Z/sOmesTrINg/A=='), 
('Remote-Addr', '127.0.0.1'), 
('Referer', 'https://server-of-origin/page.html'), 
('Accept-Language', 'en-US,en;q=0.8'), 
('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36'), 
('Origin', 'https://server-of-origin')]
&lt;/CODE&gt;&lt;/PRE&gt;

&lt;P&gt;What I am expecting is to see another tuple like: &lt;CODE&gt;('Authorization','whatever')&lt;/CODE&gt;&lt;/P&gt;</description>
      <pubDate>Wed, 14 Dec 2016 17:58:36 GMT</pubDate>
      <guid>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281246#M3533</guid>
      <dc:creator>twesthead</dc:creator>
      <dc:date>2016-12-14T17:58:36Z</dc:date>
    </item>
    <item>
      <title>Re: How to get HTTP header value in custom python web service?</title>
      <link>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281247#M3534</link>
      <description>&lt;P&gt;The auth header is protected to my knowledge.  I was never able to get it with these methods you mention.  I was able to get one by authenticating against Splunk programmatically though.  And I was also able to pass the header through to custom Splunk commands.  &lt;/P&gt;</description>
      <pubDate>Thu, 15 Dec 2016 00:41:24 GMT</pubDate>
      <guid>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281247#M3534</guid>
      <dc:creator>jkat54</dc:creator>
      <dc:date>2016-12-15T00:41:24Z</dc:date>
    </item>
    <item>
      <title>Re: How to get HTTP header value in custom python web service?</title>
      <link>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281248#M3535</link>
      <description>&lt;P&gt;Hi, thanks for your comment. Can you tell me more about "authenticating against Splunk programmatically" and "passing a header through to custom Splunk commands"?&lt;BR /&gt;
Do you mean by using username and password through the management port on endpoint 'auth/login'?&lt;/P&gt;</description>
      <pubDate>Thu, 15 Dec 2016 08:48:31 GMT</pubDate>
      <guid>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281248#M3535</guid>
      <dc:creator>twesthead</dc:creator>
      <dc:date>2016-12-15T08:48:31Z</dc:date>
    </item>
    <item>
      <title>Re: How to get HTTP header value in custom python web service?</title>
      <link>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281249#M3536</link>
      <description>&lt;P&gt;Yeah that's what I meant.  But then you've got to hard code a user/pass etc.&lt;/P&gt;

&lt;P&gt;Using a Splunk search command however, you can pass the auth token with the correct commands.conf settings.  I don't know if that's an option for you or not.  You know... Somehow I do this with my rest endpoints because I trigger a restart message after the user clicks save on setup.xml.  Let me get back to you...&lt;/P&gt;</description>
      <pubDate>Thu, 15 Dec 2016 12:19:04 GMT</pubDate>
      <guid>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281249#M3536</guid>
      <dc:creator>jkat54</dc:creator>
      <dc:date>2016-12-15T12:19:04Z</dc:date>
    </item>
    <item>
      <title>Re: How to get HTTP header value in custom python web service?</title>
      <link>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281250#M3537</link>
      <description>&lt;P&gt;In your custom rest handler use this:&lt;/P&gt;

&lt;P&gt;sessionKey=self.getSessionKey() &lt;/P&gt;

&lt;P&gt;Here's a full example:&lt;/P&gt;

&lt;P&gt;look for "#prompt user to restart splunk web"&lt;/P&gt;

&lt;PRE&gt;&lt;CODE&gt;### SCRIPT NAME: webSSL_rest.py


import splunk.admin as admin
import os, sys, requests, errno, ConfigParser
import splunk.mining.dcutils as dcu

logger = dcu.getLogger()

class webSSL(admin.MConfigHandler):
  CONF_FILE = 'webSSL'

  def setup(self):
    if self.requestedAction in (admin.ACTION_CREATE,admin.ACTION_EDIT):
      self.supportedArgs.addReqArg("certname")
      self.supportedArgs.addReqArg("cert")
      self.supportedArgs.addReqArg("key")

  def handleEdit(self, confInfo):
    if not 'certname' in self.callerArgs.data.keys() and self.callerArgs['certname']:
       raise admin.ArgValidationException, "A certname must be provided"
    if not 'cert' in self.callerArgs.data.keys() and self.callerArgs['cert']:
       raise admin.ArgValidationException, "A cert must be provided"   
    if not 'key' in self.callerArgs.data.keys() and self.callerArgs['key']:
       raise admin.ArgValidationException, "A key must be provided"   

    #handle long cert pasted in small field remove header and footer and break spaces into new rows
    certname = self.callerArgs['certname'][0]
    cert = self.callerArgs['cert'][0].replace('-----BEGIN CERTIFICATE-----','').replace('-----END CERTIFICATE-----','').replace(" ","\n")
    key = self.callerArgs['key'][0].replace('-----BEGIN RSA PRIVATE KEY-----','').replace('-----END RSA PRIVATE KEY-----','').replace(" ","\n")

    #set paths for cert &amp;amp; key
    scriptDir = sys.path[0]

    #scriptDir = C:\Program Files\Splunk\bin
    certPath = os.path.join(scriptDir,'..','etc','myauth',certname+'.pem')
    keyPath = os.path.join(scriptDir,'..','etc','myauth',certname+'.key')
    webConfPath = os.path.join(scriptDir,'..','etc','system','local','web.conf')

    #handle myauth/cert folder missing
    if not os.path.exists(os.path.dirname(certPath)):
     try:
      os.makedirs(os.path.dirname(certPath))
     except OSError as exc: 
      if exc.errno != errno.EEXIST:
       raise

    #write cert &amp;amp; key adding header &amp;amp; footer back
    with open(certPath,"w") as f:
     f.write("-----BEGIN CERTIFICATE-----" + cert + "-----END CERTIFICATE-----")    
    with open(keyPath,"w") as f:
     f.write("-----BEGIN RSA PRIVATE KEY-----" + key + "-----END RSA PRIVATE KEY-----")

    #modify &amp;amp; write web.conf
    try:
     config = ConfigParser.RawConfigParser()
     config.optionxform = str
     config.read(webConfPath)
     if not config.has_section("settings"):
      config.add_section("settings")
     config.set("settings","enableSplunkWebSSL",True)
     config.set("settings","caCertPath",certPath)
     config.set("settings","privKeyPath",keyPath)
     with open(webConfPath,"wb") as confFile:
      config.write(confFile)
    except Exception as e:
     logging.error(e)

    #prompt user to restart splunk web
    sessionKey=self.getSessionKey()
    headers = {'Authorization':''}
    headers['Authorization'] = 'Splunk ' + sessionKey  
    data = {'name':'restart_link','value':'Splunk must be restarted for changes to take effect.  [[/manager/search/control| Click here to restart from the Manager.]]','severity':'warn'}
    r = requests.post("https://localhost:8089/services/messages/new", headers=headers, data=data, verify=False)
    data = {'name':'restart_reason','value':'A user triggered the create action on app ssl_installer, and the following objects required a restart: ssl configuration','severity':'warn'}
    r = requests.post("https://localhost:8089/services/messages/new", headers=headers, data=data, verify=False)
    pass

  def handleList(self, confInfo):
   confDict = self.readConf(self.CONF_FILE)
   if None != confDict:
    for stanza, settings in confDict.items():
     for key, val in settings.items():
      if val is None:
       confInfo[stanza].append(key, "")
      else:
       confInfo[stanza].append(key, val)


  def handleReload(self, confInfo):
    pass

admin.init(webSSL, admin.CONTEXT_NONE)
&lt;/CODE&gt;&lt;/PRE&gt;</description>
      <pubDate>Thu, 15 Dec 2016 19:05:01 GMT</pubDate>
      <guid>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281250#M3537</guid>
      <dc:creator>jkat54</dc:creator>
      <dc:date>2016-12-15T19:05:01Z</dc:date>
    </item>
    <item>
      <title>Re: How to get HTTP header value in custom python web service?</title>
      <link>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281251#M3538</link>
      <description>&lt;P&gt;@twesthead, any luck with the example?&lt;/P&gt;</description>
      <pubDate>Tue, 20 Dec 2016 01:07:00 GMT</pubDate>
      <guid>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281251#M3538</guid>
      <dc:creator>jkat54</dc:creator>
      <dc:date>2016-12-20T01:07:00Z</dc:date>
    </item>
    <item>
      <title>Re: How to get HTTP header value in custom python web service?</title>
      <link>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281252#M3539</link>
      <description>&lt;P&gt;Sorry about the delay and thanks for the detailed example.&lt;BR /&gt;
I believe your example shows the implementation of a rest handler defined in  &lt;CODE&gt;restmap.conf&lt;/CODE&gt;.&lt;BR /&gt;
I am using a python controller/endpoint defined in  &lt;CODE&gt;web.conf&lt;/CODE&gt; and  &lt;CODE&gt;appserver/controllers&lt;/CODE&gt;.&lt;BR /&gt;
Therefore, my main class is not  &lt;CODE&gt;splunk.admin.MConfigHandler&lt;/CODE&gt; but  &lt;CODE&gt;splunk.appserver.mrsparkle.controllers.BaseController&lt;/CODE&gt;.&lt;/P&gt;

&lt;P&gt;I feel like I haven't provided enough information on my general goal.&lt;BR /&gt;
The background to this question is in &lt;A href="https://answers.splunk.com/answers/478686/how-to-define-a-custom-python-controller-to-pass-c.html"&gt;this other question&lt;/A&gt;.&lt;/P&gt;

&lt;P&gt;Since that unanswered question, I decided to authenticate and authorize users myself:&lt;BR /&gt;
1. I have created an  &lt;CODE&gt;auth/login&lt;/CODE&gt; custom controller that takes (admin, password) and returns a sessionKey. (using  &lt;CODE&gt;splunklib.client&lt;/CODE&gt; module)&lt;BR /&gt;
2. All my other web services take the sessionKey as a parameter and check if it is valid to authorize the request.&lt;BR /&gt;
3. I find it ugly to pass the sessionKey as a param and I would like to pass it in an header that looks appropriate.&lt;/P&gt;</description>
      <pubDate>Tue, 20 Dec 2016 09:13:32 GMT</pubDate>
      <guid>https://community.splunk.com/t5/Splunk-Dev/How-to-get-HTTP-header-value-in-custom-python-web-service/m-p/281252#M3539</guid>
      <dc:creator>twesthead</dc:creator>
      <dc:date>2016-12-20T09:13:32Z</dc:date>
    </item>
  </channel>
</rss>

